关于C++单例模式下m_pinstance指向空间销毁问题,m_pInstance的手动销毁经常是一个头痛的问题,内存和资源泄露也是屡见不鲜,能否有一个方法,让实例自动释放。

解决方法就是定义一个内部垃圾回收类,并且在Singleton中定义一个此类的静态成员。程序结束时,系统会自动析构此静态成员,此时,在此类的析构函数中析构Singleton实例,就可以实现m_pInstance的自动释放。

附上测试代码

复制代码

 1 #include <iostream> 2 using namespace std; 3  4 class Singleton 5 { 6 public: 7     static Singleton *GetInstance() 8     { 9         if (m_Instance == NULL)10         {11             m_Instance = new Singleton();12             cout<<"get Singleton instance success"<<endl;13         }14         return m_Instance;15     }16 17 private:18     Singleton(){cout<<"Singleton construction"<<endl;}19     static Singleton *m_Instance;20 21     // This is important22     class GC // 垃圾回收类23     {24     public:25         GC()26         {27             cout<<"GC construction"<<endl;28         }29         ~GC()30         {31             cout<<"GC destruction"<<endl;32             // We can destory all the resouce here, eg:db connector, file handle and so on33             if (m_Instance != NULL)34             {35                 delete m_Instance;36                 m_Instance = NULL;37                 cout<<"Singleton destruction"<<endl;38                 system("pause");//不暂停程序会自动退出,看不清输出信息39             }40         }41     };42     static GC gc;  //垃圾回收类的静态成员43 44 };45 46 Singleton *Singleton::m_Instance = NULL;47 Singleton::GC Singleton::gc; //类的静态成员需要类外部初始化,这一点很重要,否则程序运行连GC的构造都不会进入,何谈自动析构48 int main(int argc, char *argv[])49 {50     Singleton *singletonObj = Singleton::GetInstance();51     return 0;52 }

复制代码


运行结果: