Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

C++ Singleton design pattern

As of late, I've chanced upon an acknowledgement/execution of the Singleton configuration design for C++. It has resembled this (I have embraced it from the genuine model):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton
instance;
};

From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.
My fundamental inquiry is, how would I carry out it in the correct manner?
by

2 Answers

espadacoder11
You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.

I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):

class Singleton
{
private:
Singleton();

public:
static Singleton& instance()
{
static Singleton INSTANCE;
return INSTANCE;
}
};

It has no dynamic memory allocation.
kshitijrana14
Another non-allocating alternative: create a singleton, say of class C, as you need it:
singleton<C>()

using
template <class X>
X& singleton()
{
static X x;
return x;
}

Login / Signup to Answer the Question.