I want to implement the singleton pattern in a header only c++ library. (Please refrain from sharing your opinion on the pattern itself!) This would be trivial if I could rely on the compiler implementing thread safe c++11 function-local static-duration object initialization. i.e.
static inline MyClass& singleTon()
{
static MyClass instance;
return instance;
}
Unfortunately MSVC prior to 2015 does not comply with this standard. See "Magic Statics" so I have tried to implement it through a class:
#include <mutex>
/**
* Header only implementation of the singleton pattern.
* Use like this:
* MyClass& singleton = SingleTon<MyClass>().get();
*/
template<class Type>
struct SingleTon
{
static std::unique_ptr<Type> instance;
static std::once_flag flag;
Type& get()
{
auto& capture = instance;// lambdas can't capture static members
std::call_once(flag, [&capture] { capture.reset(new Type{}); });
return *instance.get();
}
};
template<class Type>
std::unique_ptr<Type> SingleTon<Type>::instance;
template<class Type>
std::once_flag SingleTon<Type>::flag;
So my function now looks like:
static inline MyClass& singleton()
{
return SingleTon<MyClass>().get();
}
I hope that this function is thread safe given that the ctor of Type
is nothrow.