Tutorial: HowTo code a C++ Singleton
On the internet you can find plenty of examples for a singleton in C++. Most of then include a memory leak.
Here I show an example without a memory leak:
singleton.cpp |
#include <iostream> class Singleton { private: Singleton() { std::cout << "Constructor Singleton" << std::endl; } ~Singleton() { std::cout << "Destructor Singleton" << std::endl; } Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; public: static Singleton& GetInstance() { static Singleton instance; return instance; } unsigned long long GetAddress() { return reinterpret_cast<unsigned long long>(this); } }; int main() { std::cout << "Starting Main" << std::endl; Singleton& instance1 = Singleton::GetInstance(); unsigned long long address1 = instance1.GetAddress(); std::cout << "Address of instance 1: " << address1 << std::endl; Singleton& instance2 = Singleton::GetInstance(); unsigned long long address2 = instance2.GetAddress(); std::cout << "Address of instance 2: " << address2 << std::endl; std::cout << "Terminating Main" << std::endl; } |
The output of the program is similar to the following (the address will probeabely be different:
Starting Main Constructor Singleton Address of instance 1: 6297106 Address of instance 2: 6297106 Terminating Main Destructor Singleton |
As you can see, first of all main is started.
Then the first GetInstance call initializes the singleton, the constructor is executed.
We print the address of the instance.
The second call to GetInstance will return the same instance.
The second printed address is the same so we have only one instance.
After main has terminated the destructor will be executed. Most examples on the Internet miss that point.
Important to consider:
- Constructor and Destructor are private.
- GetInstance returns a reference (not a pointer) to an instance that is declared static within the method.
- Copy constructor and assignment operator are deleted to prevent copies of the singleton.
- Never use new operator explicitly. You are not able to correctly clean up the singleton with an explicit delete. Let the compiler do this for you, the compiler can do it right.
I hope this mini tutorial helped you.