版本一 Reference:http://tech.ddvip.com/2009-04/1238585011113136.html
class CSingleton:
{
// 其它成员
public:
static CSingleton * GetInstance(){。。。}
private:
CSingleton(){};
static CSingleton * m_pInstance;
class CGarbo // 它的唯一工作就是在析构函数中删除CSingleton的实例
{
public:
~CGarbo()
{
if (CSingleton::m_pInstance)
delete CSingleton::m_pInstance;
}
};
static CGarbo Garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数
}
版本二 Reference:http://blog.csdn.net/windboyzsj/article/details/2790485
#include <iostream.h>
class Singleton
{
public:
~Singleton(){cout<<"singleton deconstruct"<<endl;}
static Singleton* Instance()
{
if (_instance == NULL)
{
_instance = new Singleton();
static Cleaner cl; //延迟到这里
}
return _instance;
}
void Print(char* str)
{
cout<<"singleton print:"<<str<<endl;
}
private:
Singleton(){cout<<"singleton construct"<<endl;}
static Singleton* _instance;
class Cleaner
{
public:
Cleaner(){cout<<"cleaner construct"<<endl;}
~Cleaner()
{
cout<<"cleaner deconstruct"<<endl;
if(Singleton::Instance())
delete Singleton::Instance();
}
};
};
Singleton* Singleton::_instance = NULL;
int main(int argc, char* argv[])
{
Singleton::Instance()->Print("print 1");
Singleton::Instance()->Print("print 2");
return 0;
}
版本三 Reference:http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt
来自IBM的一些研究性文章,此方法也可以借用一下,本人英语比较烂就不献丑了,更详细查看reference,里面写的比较详细
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton() { }
friend class SingletonDestroyer;
virtual ~Singleton() { }
private:
static Singleton* _instance;
static SingletonDestroyer _destroyer;
};
Singleton* Singleton::_instance = 0;
SingletonDestroyer Singleton::_destroyer;
Singleton* Singleton::Instance () {
if (!_instance) {
_instance = new Singleton;
_destroyer.SetSingleton(_instance);
}
return _instance;
}
class SingletonDestroyer {
public:
SingletonDestroyer(Singleton* = 0);
~SingletonDestroyer();
void SetSingleton(Singleton* s);
private:
Singleton* _singleton;
};
SingletonDestroyer::SingletonDestroyer (Singleton* s) {
_singleton = s;
}
SingletonDestroyer::~SingletonDestroyer () {
delete _singleton;
}
void SingletonDestroyer::SetSingleton (Singleton* s) {
_singleton = s;
}