1 #ifndef SINGLETONHOLDER_INC 2 #define SINGLETONHOLDER_INC 3 4 template<class T> 5 class SingletonHolder 6 { 7 public: 8 static T* Instance() 9 { 10 if(!pInstance_) 11 pInstance_=new T; 12 return pInstance_; 13 } 14 private: 15 SingletonHolder(){}; 16 SingletonHolder(const SingletonHolder&); 17 SingletonHolder& operator=(const SingletonHolder&); 18 ~SingletonHolder(){}; 19 static T* pInstance_; 20 }; 21 22 template<class T> 23 T* SingletonHolder<T>::pInstance_=0; 24 25 26 #endif 27 28 29 #ifndef INS 30 #define INS SingletonHolder<CGlobal>::Instance() 31 #endif
结合模板和宏定义,可以很方便的单例化任何类
时间: 2024-10-18 09:01:49