C++ 单件
我构造的单件(从Java代码改过来的):
// Singleton.h: interface for the CSingleton class.class CSingleton {private: CSingleton(); ~CSingleton();private: static CSingleton *m_pInstance;public: static CSingleton *GetInstance(); void Release();};//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CSingleton::CSingleton(){ cout<<"object is ["<<this<<"] Do <<<Construction"<<endl;}CSingleton::~CSingleton(){ cout<<"object is ["<<this<<"] Do Destruction>>>"<<endl;}//////////////////////////////////////////////////////////////////////CSingleton* CSingleton::m_pInstance = NULL;CSingleton* CSingleton::GetInstance(){ if (NULL == m_pInstance) { m_pInstance = new CSingleton(); } return m_pInstance;}void CSingleton::Release() { if (NULL != m_pInstance) { delete m_pInstance; m_pInstance = NULL; } }CSingleton *single = CSingleton::GetInstance(); single->Release();
class CA {private: CA(); ~CA();private: static CA staticInstance;public: void HelloWorld(); static CA* GetInstance();};//---------------------------//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CA::CA(){ cout<<"object is ["<<this<<"] Do <<<Construction"<<endl;}CA::~CA(){ cout<<"object is ["<<this<<"] Do Destruction>>>"<<endl;}//////////////////////////////////////////////////////////////////////CA* CA::GetInstance(){ return &staticInstance;}void CA::HelloWorld(){ cout<<" Singleton Design"<<endl;}
Single::~Single(){
// 析构
}
Single* Single::Instance()
{
if ( __pInstance.get()==0 )
{
__pInstance.reset( new Single() );
}
return __pInstance.get();
}
/* 要点1.必须隐藏构造函数,否则用户还是可以直接实例化对象
要点2.必须在实现文件(CPP)里定义静态成员,否则会导致“没有决议的符号”编译错误
要点3.实现一个Instance函数来提供全局的访问
要点4.形式是死的,但一般都包含指针而不是直接在类中定义对象,因为单实例模式的一个重要应用是延迟对象实例化的时间,即只有在需要的时候才将其实例化
*/
以上为个人愚见
[解决办法]
单件,C++实现中如何才能保证线程安全???这个问题我想了很久都没有想明白.
[解决办法]
mark
[解决办法]