One way of making a singleton with thread-safe initialization, guaranteed by the standard as of C++11. is:
class SomeSingleton {
public:
static SomeSingleton& instance() {
static SomeSingleton instance_;
return instance_;
}
private:
SomeSingleton() {
...
}
};
This is thread-safe, because local static variable initialization is thread-safe in C++11. The relevant standard document, N3485, says in section 6.7.4:
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
with footnote:
The implementation must not introduce any deadlock around execution of the initializer.
You can abstract into a nice template base class with CRTP:
//Singleton template definition
template <typename TDerived>
class Singleton {
static_assert(is_base_of<Singleton, TDerived>::value, "Singleton: unexpected Derived template parameter");
public:
static TDerived& instance() {
static TDerived instance_;
return instance_;
}
protected:
Singleton() {
}
};
// SomeSingleton definition, using the Singleton template
class SomeSingleton : public Singleton<SomeSingleton> {
...
};