Singleton in C++
Following singleton can be used in multi-threaded environment:
class SingletonClass { public: static SingletonClass* getInstance(); void init(); private: SingletonClass(); static SingletonClass* _sharedInstance; }; SingletonClass* SingletonClass::_sharedInstance= nullptr; std::mutex singleton_init_mutex; SingletonClass* SingletonClass::getInstance() { static SingletonClass singleton; static bool initialized= false; if (!_sharedInstance) { _sharedInstance= &singleton; std::lock_guard<std::mutex> guard(singleton_init_mutex); // expensive initialisation will be done with lock if (!initialized) { _sharedInstance->init(); _initialized= true; // because of the lock second thread will not initialize again } } }