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

private:
    static std::unique_ptr<CSingleton> m_instance;
    static std::once_flag m_onceFlag;
    CSingleton(void);
    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()
{
    std::call_once(m_onceFlag,
        [] {
            m_instance.reset(new CSingleton);
    });
    return *m_instance.get();
}

No comments:

Post a Comment