C++单例模式

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();


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章