singelton object and resource deallocation ??

Jan 10, 2011 at 8:56am
Hi,

I am using classical singelton pattern in C++ for a class (using a private static pointer to class instance within the class). Now, I am unsure about the deallocation(release of resources) by this static pointer. I am not calling explicitly the "delete" on that private instance in my normal code which can invoke destructor. My intention was that it should get deallocated at program exit and should free its resources but I am not sure that it is doing it.

I try to simulate with following example (please ignore syntax issues as I formulated it here):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Singelton
{
   private: 
       static Singleton* instance;
       // Constructor
       // Private data from other classes which should get free at program exit
   public:
      Singelton* getInstance()
      {...}
      // Destructor where I write code to free other pointers that this instance refers to from other classes
}

int main()
{
   // some code
   
   // if I comment out the following line, Will it still call destructor for Singleton??
   delete Singleton::getInstance();
}


I have tried to see by having printf in destructors but it does not show them which I suppose means that it does not do deallocation automatically at end??


Thanks in advance for your help.

--
Usman.
Jan 10, 2011 at 11:27am
give your singleton class a static deleteInstance function

1
2
3
4
5
6
7
8
void deleteInstance()
{
    if (instance)
    {
        delete instance;
        instance = 0;
    }
}


and then call it whenever appropriate
Jan 10, 2011 at 11:59am
enliten

Even the singleton pattern is simple enough, there are two problems arising with using one.

The first: how to make singleton thread safe?
The second: when and how singleton object has to be destroyed?

I recommend you to read Pattern Hatching by John Vlissides (http://www.amazon.com/Pattern-Hatching-Design-Patterns-Applied/dp/0201432935 ).
Jan 10, 2011 at 3:14pm
Thankyou so much for your kind replies.

I was mainly interested in some implicit way to delete resources at the end of program execution.
Besides your suggestions, I found http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt which is from the book you mentioned about how to kill singelton.

Thanks and happy coding
Topic archived. No new replies allowed.