class Singleton
{
public:
~Singleton(){}
static Singleton* Instance()
{
if (_instance == NULL)
{
_instance = new Singleton();
}
return _instance;
}
private:
Singleton(){}
static Singleton* _instance;
};
Singleton* Singleton::_instance = NULL;
这里面的_instance 应该在哪里delete呢?
{
public:
~Singleton(){}
static Singleton* Instance()
{
if (_instance == NULL)
{
_instance = new Singleton();
}
return _instance;
}
private:
Singleton(){}
static Singleton* _instance;
};
Singleton* Singleton::_instance = NULL;
这里面的_instance 应该在哪里delete呢?
class CSingleton{
private:
CSingleton(){}
CSingleton & operator=(CSingleton & o){}
CSingleton & operator()(CSingleton & o){}
static CSingleton *instance; public:
virtual ~CSingleton()
{
if(NULL!=instance)
{
delete(instance);
instance=NULL;
}
}
CSingleton & getInstance()
{ if(NULL==instance)
{
instance=new CSingleton();
}
return *instance; }
};
在 虚构函数 里调用 delete ,其实,程序都没有运行到这里来.不会调用 虚构函数,但系统会在程序退出后来回收它的申请的空间.
原因
1 程序退出.删除 静态的指针(注意这是删除的是静态的指针 不是它指向的对象)
所以程序不会调用到它的虚构函数.