Skip to main content
gamedev.net
🔒 Locked

destroying singleton instances ?

Started by bg3ntl 3 replies 450+ views
Original Post
bg3ntl
bg3ntl
well ok i understand singletons now and how to use them etc. when do they get destroyed ? do u create a destroy function and call that when u want to release the instance you have created ? or can u just put a call to delete m_singleton in the destructor. when the app quits will it automatically call the destructor for any remaining objects ? thanks for your help bg3ntl
regards,bg3ntl' That's a nice little nothing you are almost wearing. '
Sandman
Sandman
A lot depends on how you implemented your singleton. If you do it the ''usual'' way, using a static member pointer to a CSingleton, which you create using new the first time the GetInstance() function is called, the destructor never gets called unless you explicitly delete the singleton . For this reason, I prefer to use this method for my singletons - its cleaner and the destructor is called automagically when the program exits.

  
class CSingleton
{
private:
CSingleton()
{
// constructor stuff goes here

}
public
~CSingleton()
{
// Destructor stuff goes here

}
CSingleton* GetInstance()
{
static CSingleton instance;
return &instance
}
};

bg3ntl
bg3ntl
why is the destructor called in your case ?

yes you are right, i am doing it the usual way with a static class member m_singleton and a static accessor function.

is it because you are creating a static variable that has a lifetime equal to that of the program exectution ?

if that is true, how come a static member variable doesnt behave the same way ?

bg3ntl
regards,bg3ntl' That's a nice little nothing you are almost wearing. '
kvh
kvh
try this post
bg3ntl
bg3ntl
thnx kvh, that post was excellent. i never knew that static vars were destroyed in FILO manner. now i see the difference between the two implementations, one is created in free space and one is just a static var destroyed at the end of program execution.

thnx a lot!

bg3ntl
regards,bg3ntl' That's a nice little nothing you are almost wearing. '

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.