网上找的,记录一下
#pragma once
template <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())