My question is when the heap is allocated using: single = new Singleton(), where does the heap get releaed? Should we add delete single in destructor ~Singleton(), please help.
Certainly you cannot free it in the destructor for two reasons: 1) the destructor will never run, and 2) if it did, you'd end up with an infinite loop.
If you want the object's destructor to run when the program exits, then implement it this way:
(Note: your implementation of the Singleton pattern was incomplete in
that it allowed copy constructor and assignment, both of which break
the singleton pattern. My code above also fixes that).
class Singleton
{
public:
//here all your staff
//please don't call this method, it was called automatically
staticvoid terminate()
{
delete single;
single = 0;
}
};
class SingletonDeletor
{
public:
~SingletonDeletor()
{
Singleton::terminate();
}
};
//in some cpp file you need to declare static variable of SingletonDeletor
static SingletonDeletor sSingletonDeletor;
jsmith's solution is what I suggest. It doesn't instantiate the instance until you use it and it cleans it up when the program exits. What's not to like about that?
There is a small difference. It's memory usage, in my case I use heap, in jsmith's case data segment is used. The difference may be not sensitive for desktops, but for embedded systems it's prefer to use heap.