Singleton design pattern c++ example
The singleton design pattern is a Creational design pattern which ensures a class has only one instance and provides a global point of access to that instance. A simple UML class diagram for singleton class is shown below.
The simple and lazy initialization of singleton class example c++ code is below.
using namespace std;
static Singleton *GetInstance (void)
if (instance == 0)
// Critical segment.
instance = new Singleton;
void othermethod (void)
cout << "hello singleton" << endl;
Singleton (Singleton const &); //need no implementation
void operator= (Singleton const &); // need no implementation
static Singleton *instance;
//initializing Singleton class static data member.
Singleton::instance = 0;
int main ()
// how to use
Singleton::GetInstance ()->othermethod ();
Note: The above implementation is good in case of single threaded environment or single threaded application. But it is not reliable in multi threaded application. Even in case of single threaded environment or application, an interrupt can be problematic.
How classic singleton design pattern is problematic for multi threaded application?
From the above figure it is clear that there are two objects even class is singleton.
what is solution of above problem?
- Synchronizing the critical section is solution.
- Look at the above code , the critical section is the section where new instance is getting called (line no 11).
- Double check locking design pattern is a solution which make the singleton thread safe. Read next link to know more about “Double check locking“