[Design Pattern/C++] Modern C++ Thread-Safe Singleton Template
Basic Programming/Design Pattern 2016. 1. 25. 16:41-Thread-Safe Singleton Template (Modern C++)-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <iostream> #include <thread> #include <mutex> template <class T> class Singleton { protected: Singleton() {}; ~Singleton() {}; Singleton(const Singleton& other) {}; private: static std::once_flag chkSingle; static std::shared_ptr<T> pInstance; static void destroy() { if (pInstance != nullptr) { pInstance.reset(); pInstance = nullptr; } } public: static T& getInstance() { std::call_once(chkSingle, []() { pInstance.reset(new T()); std::atexit(destroy); }); return *(pInstance.get()); } }; template <class T> std::shared_ptr<T> Singleton <T>::pInstance = nullptr; template <class T> std::once_flag Singleton <T>::chkSingle; | cs |