So, classic simple Singleton realization is following:
class Singleton
{
private:
static Singleton* singleton;
Singleton() {}
public:
static Singleton* getInstance();
};
cpp-file:
Singleton* Singleton::singleton = 0;
Singleton* Singleton::getInstance()
{
if (!singleton)
{
singleton = new Singleton;
}
return singleton;
}
I see memory leak here - 'cos there is no delete for the new. But in C++ there isn't static destructor, so we just don't care about this memory leak?
When a variable local to a function is declared "static", it means that it isn't allocated on the stack - and that its value persists from one call to the next.
Why you should avoid such code, when there is no matching
delete
fornew
While there is no actual memory leak (in most modern operating systems), worse thing is that your
Singleton
destructor doesn't get called. And if you acquire some resources, they propbably would leak.What can be done here
Use smart pointer to store instance, consider
std::unique_ptr
(with C++11) orboost::auto_ptr
A memory leak is more than just an allocation with no matching free. It's when you have memory that could be reclaimed because the object is no longer in use, but which doesn't ever actually get freed. In fact, many memory leaks are cases where there is code in the program to deallocate memory, but for whatever reason it doesn't get called (for example, a reference cycle). In fact, there's a lot of research on how to detect these sorts of leaks; this paper is an excellent example of one such tool.
In the case of a singleton, we don't have a leak because that singleton exists throughout the program. Its lifetime is never intended to end, and so the memory not getting reclaimed isn't a problem.
That said, the code you have above is not how most people would implement a singleton. The canonical C++ implementation would be something like this:
.cpp file:
Now there's no dynamic allocation at all - the memory is allocated by the compiler and probably resides in the code or data segment rather than in the heap. Also note that you have to explicitly disallow copying, or otherwise you could end up with many clones of the singleton.
The other advantage of this is that C++ guarantees that at program exit (assuming the program terminates normally), the destructor for
theInstance
will indeed fire at the end of the program. You can thus define a destructor with all the cleanup code you need.Hope this helps!