# DirectX Objects in a struct

I am playing around directx lately and I am learning from rasterek.com tutorials. He passes pointers to directx objects (like ID3D11Device, ID3D11DeviceContext etc.) for almost every class he creates. Wouldn't be a better approach to create some kind of singleton or event a simple struct that keeps all of the objects? I don't know too much about game engine designs and I don't understand his purpose, for me it's just more work to do.

Example: His code:

bool Class::initialize( ID3D11Device* device ) {
device->doSmth();
}


My idea:

struct DXObj {
static ID3D11Device* device;
}
bool Class::initialize() {
DXObj::device->doSmth();
}

• A DirectX object is nothing more than bits moving in and out of memory. – Andy Harglesis Dec 28 '12 at 22:26

This is more just a general programming question, and in general all of these kinds of questions boil down to subjective decisions on your part given that there are pros and cons of any given approach.

But in general, your idea isn't necessarily a good one given that all you're really doing is making those objects globals. Global accessibility might mean you don't have to pass them around as much (possibly making your life easier), but it also means you might be inclined to make "sloppy" architecture decisions (which will make your life harder when/if you get around to refactoring). You should be striving to encapsulate as much as possible in one section of the code base to reduce dependencies and so on.

Just look up any of hundreds of articles on whether or not you should make things global and you'll find a lot more on the subject matter.

Problems like these are usually solved with something called a "context" variable - an "umbrella" structure that keeps all session-local state (variables that could also be global) inside it. Whenever you need something from it, you pass the context or "make it current" (set a global variable that is a pointer to a context). That way, you have at most one global variable instead of many.

However, since this method is widely accepted and used despite globals being hated all around the world, this is somewhat close to hypocrisy. So until there's a real need for such workarounds (platform limits or the requirement to have multiple sessions/states), using globals is just fine. Using too many of them can make code hard to understand, that's about the only problem you could bump into so far.

So I can confirm your suspicion. The code sample you posted definitely bad. The loose ID3D11DeviceContext should be a member of a class somewhere.

But yes, you should write a single class to represent your main game object (or main window object, whatever you like to call it), and inside that class have a single ID3D11DeviceContext.
You don't need to declare your ID3D11DeviceContext static. No idiot will try to create 2 instances of your DxObj.