Destruction of singletons.

Started by
5 comments, last by Emmanuel Deloget 18 years, 10 months ago
I have a singleton class in my app. I certain that I need it to be a singleton as there should only ever be one of this class and it needs to be accessed from almost every other class in the app (it's my logging class). I've run into a snag though - I can't seem to find a nice way to run the destructor for the function when the app ends. At the minute I'm initialising a boost::scoped_ptr with a pointer to my singleton instance in my main() function, but this seems really hacky. Does anyone have a nice way to ensure that the destructor is called?
Advertisement
// in headerconst SingletonObject &Singleton();// in sourceconst SingletonObject &Singleton(){        static SingletonObject so;        return so;}

this is the third time i write a response, the other two was long and descriptive, but I got http500ed... but now i'll just write: check out the atexit function...
"I could be off endlessly perfecting my 3d engine, but instead I am cursed with the task of actually finishing something, it sucks."
A brief overview of Singletons. My favorite is a variation on what he calls the "Nifty Counter."

CM
If the instance object itself of the singleton is created as static, then it will automatically be destroyed upon app exit. However, there is no goverened rule upon the order of destruction of statically allocated memory.
I've been using a static ptr that is initialised to NULL. The instance of the singleotn is created on first use.

If static objects are destroyed, could I just change my ptr to an auto_ptr?
Quote:Original post by Nitage
I've been using a static ptr that is initialised to NULL. The instance of the singleotn is created on first use.

If static objects are destroyed, could I just change my ptr to an auto_ptr?


You can, but you have to remember that don't have any control on the order of destruction of global (and static) objects.

Regards,

This topic is closed to new replies.

Advertisement