Saturday, May 24, 2014

Thread-safe Singleton with C++11

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
    virtual ~CSingleton();
    static CSingleton& GetInstance();

    static std::unique_ptr<CSingleton> m_instance;
    static std::once_flag m_onceFlag;
    CSingleton(const CSingleton& src);
    CSingleton& operator=(const CSingleton& rhs);

//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()
        [] {
            m_instance.reset(new CSingleton);
    return *m_instance.get();

No comments:

Post a Comment