关于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 }
运行结果:
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。