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?
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). 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
theInstancewill indeed fire at the end of the program. You can thus define a destructor with all the cleanup code you need.Hope this helps!