////////////////////////////////////////////////////////////////////////////////////// // Singleton.h: interface for the Singleton class. ////////////////////////////////////////////////////////////////////////////////////// // ex) sample // // class Test : public Singleton < Test > // { // public: // Test* Sample( int num ); // //... // }; // // // // #define g_Test Test::GetSingleton() // // void SomeFuncton( void ) // { // Test * pTemp = Test::GetSingleton().Sample( 7 ); // // or Test * pTemp = g_Test.Sample( 7 ); // } // ////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------- # 颇老疙 : Singleton.h # 汲 疙 : interface for the Singleton template class. # 郴 仿 : # 厚 绊 : ---------------------------------------------------------------------------*/ #ifndef __SINGLETON_H__ #define __SINGLETON_H__ /////////////////////////////////////////////////////////////////////////////// // include define statement /////////////////////////////////////////////////////////////////////////////// #include "assert.h" #include #include /////////////////////////////////////////////////////////////////////////////// // class define statement /////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------- # 努贰胶 疙 : Singleton # 何葛努贰胶 : 绝澜 # 曼炼努贰胶 : 绝澜 # 包府氓烙磊 : Voidhoon # 汲 疙 : # 函 荐 : # 郴 仿 : # 巩 力 痢 : ---------------------------------------------------------------------------*/ template class Singleton { public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static void SetSingleton(T* pT) { assert(pT); instance.reset(pT); } static T* GetSingleton(void) { std::call_once(flag, []() { instance.reset(new T); }); return instance.get(); } static T* GetSingletonPtr(void) { std::call_once(flag, []() { instance.reset(new T); }); return instance.get(); } static T& GetSingletonInstance(void) { std::call_once(flag, []() { instance.reset(new T); }); return *instance.get(); } protected: Singleton() = default; virtual ~Singleton() = default; private: static std::unique_ptr instance; static std::once_flag flag; }; template std::unique_ptr Singleton::instance = nullptr; template std::once_flag Singleton::flag; #endif