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呢?

解决方案 »

  1.   


    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;        }
    }; 
      

  2.   

    重写析构函数,析构函数中delete
      

  3.   

    单件因为生存期是全局的,可以不考虑销毁,让进程退出时自己销毁;当然可能需要在析构时作一些特殊操作,那么可以提供一个销毁用的静态函数供进程退出的时候调用,比如放在C...App的ExitInstance()或者析构函数中调用。
      

  4.   

    同意7楼看法.但是你如何觉的自己来释放好一点.那么可以用 auto_ptr来保存申请的空间.
    在 虚构函数 里调用 delete ,其实,程序都没有运行到这里来.不会调用 虚构函数,但系统会在程序退出后来回收它的申请的空间.
    原因
     1 程序退出.删除 静态的指针(注意这是删除的是静态的指针 不是它指向的对象)
       所以程序不会调用到它的虚构函数.