c++单例

来源:互联网 发布:c语言 矩形 rect 编辑:程序博客网 时间:2024/06/09 23:05

网上找的,记录一下

#pragma oncetemplate <class T>class Singleton{public:          static inline T* instance();     private:        Singleton(void){}        ~Singleton(void){}       Singleton(const Singleton&){}      Singleton & operator= (const Singleton &){}        static std::auto_ptr<T> _instance;}; template <class T>std::auto_ptr<T> Singleton<T>::_instance; template <class T> inline T* Singleton<T>::instance(){    if( 0== _instance.get())       {                  _instance.reset ( new T);     }              return _instance.get();}//Class that will implement the singleton mode,//must use the macro in it's delare file#define DECLARE_SINGLETON_CLASS( type ) \    friend class std::auto_ptr< type >;\    friend class Singleton< type >;

用法是:

类声明头部加入

    DECLARE_SINGLETON_CLASS(TaskManager);

头文件声明调用宏(非必要)

#define TaskManagerInstance (Singleton<TaskManager>::instance())
0 0