|
Pol
Revision:e081b86
|
00001 /* 00002 History 00003 ======= 00004 00005 Notes 00006 ======= 00007 00008 */ 00009 00010 #ifndef CLIB_SINGLETON_H 00011 #define CLIB_SINGLETON_H 00012 namespace Pol { 00013 namespace Clib { 00014 template <typename T> 00015 class Singleton 00016 { 00017 private: 00018 static void _cleanup() { delete _instance; _instance = NULL; } 00019 public: 00020 static T* instance() 00021 { 00022 if( !_instance ) 00023 { 00024 std::lock_guard<std::mutex> lock( _SingletonMutex ); //critical double check 00025 if( !_instance ) 00026 { 00027 _instance = new T(); 00028 atexit( &Singleton<T>::_cleanup ); 00029 } 00030 } 00031 return _instance; 00032 } 00033 private: 00034 static T* _instance; 00035 static std::mutex _SingletonMutex; 00036 protected: 00037 Singleton() {} 00038 ~Singleton() {} 00039 private: // Forbid copies 00040 Singleton( Singleton& ); 00041 Singleton& operator=( Singleton& ); 00042 }; 00043 template <typename T> T* Singleton <T>::_instance = NULL; 00044 template <typename T> std::mutex Singleton <T>::_SingletonMutex; 00045 } 00046 } 00047 #endif 00048