Note: see my more recent article “Implementing a Thread-Safe Singleton with C++11 Using Magic Statics” for a more modern solution.

C++11 makes it easier to write a thread-safe singleton. Here is an example. The class definition of the singleton looks as follows:

#include <memory> #include <mutex> class CSingleton { public: virtual ~CSingleton() = default; static CSingleton& GetInstance(); private: static std::unique_ptr<CSingleton> m_instance; static std::once_flag m_onceFlag; CSingleton() = default; CSingleton(const CSingleton& src) = delete; CSingleton& operator=(const CSingleton& rhs) = delete; };

The implementation of the GetInstance() method is very easy using C++11 std::call_once() and a lambda:

std::unique_ptr<CSingleton> CSingleton::m_instance; std::once_flag CSingleton::m_onceFlag; CSingleton& CSingleton::GetInstance() { std::call_once(m_onceFlag, [] { m_instance.reset(new CSingleton); }); return *m_instance.get(); }