C++ Order Of Destruction

Started by
10 comments, last by Evil Steve 16 years, 9 months ago
Quote:Original post by OrangyTang
I've previously solved initialisation order problems with 'globals' being static within methods (eg. Obj& getObj() { static Obj o; return o; } ), however I have no idea if the destruction order of these objects is well defined or not.

It is "relatively well defined". Static objects are destroyed in the inverse order of the completion of their constructor.

Advertisement
Quote:Original post by David Neubelt
1) Have the memory manager as a global object at the top of your main application. Obj files that are for the executable get initialized before library statics. Also, the the order of globals, within a compilation unit, are initialized from top down. If your memory manager is the first global variable in that file and doesn't depend, contain or inherit from any other class then you'll have it being initialized first.
I've tried this. The STL global is always constructed before any globals in my code, no matter what order the globals are defined in. Presumably it's in a lib init segment, so it's always constructed before user globals (Which makes sense, you don't want a user-defined global trying to use STL stuff and having it blow up).

Quote:Original post by David Neubelt
2) The most portable way (I define portable being this has worked for me on the most platforms and most compilers) is to re-write the CRT initialization and shut down code. Have your own function get called instead of the CRT start up. You can do this through the linker option /ENTRY in visual studio. It's not too hard and most of the time you can copy and paste the compilers CRT code, remove the stuff you don't need, and stick your memory manager initialization before the global variables are constructed.
That's possible I suppose, but it's also pretty major overkill for this [smile]

This topic is closed to new replies.

Advertisement