I have a global variable which is an instance of a class. This class created an image in its constructor (directX).
The problem is that I am getting an access violation at runtime but the code compiles. I think the problem is that the class constructor is being called before the initialisation done in the winmain function.
so what I want to know is
-
has anyone encountered this problem and knows of a solution.
-
What is the lifespan of a global, i know variables declared in a function are lost after it returns and that the compiler looks through the code the see if everything matches which is why we have to prototype functions but where do global’s come into the equation.
You probably want to look at something like the singleton pattern if you really want to have one instance of a global, that can be initialized after the initialisation is done (essentially, the image would be constructed the first time you referenced it after which you’d use the pre-constructed version).
Globals are constructed (in undefined order), before your winmain is called. They stay there until your program exits (at which point I believe the destructors are called in an undefined order)..
Another (possibly simpler) alternative you could use would be to change your global from an instance of the class to a pointer to it… then you’d have something like:
Then everywhere you’re currently referencing your global, you could reference it via a pointer instead..