class Singleton{
static std::auto_ptr m_pInstance;
protected: //拒绝任何形式的手动创建
Singleton(){}
public:
~Singleton(){}
//返回单件实例
static Singleton* Instance()
{
if(!m_pInstance.get())
{
m_pInstance = std::auto_ptr(new Singleton());
}
return m_pInstance.get();
}
};
//以上是一个完整的单例实现,然而这个实现不是线程安全的,在多线程环境下,需要使用线程互斥获取单件实例,一个优雅的方法见《double-check》
//需要多个单件子类,可做下面的宏定义
#define DEFINE_SINGLETON(cls)\
private:\
static std::auto_ptr m_pInstance;\
protected:\
cls(){}\
public:\ ~cls(){}\
static cls* Instance(){\
if(!m_pInstance.get()){\
m_pInstance = std::auto_ptr(new cls());\
}\ return m_pInstance.get();\
}#define IMPLEMENT_SINGLETON(cls) \
std::auto_ptr cls::m_pInstance(NULL);
//这样实现一个单例类如下:
//.h文件
class Single {
DEFINE_SINGLETON(Single);
public://your interfaces here...
};
//.cpp文件
IMPLEMENT_SINGLETON(Single);
//使用:
Single* pSingle = Single::Instance();