////////////////////////////////////////////////////////////////////////////////////// // 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