zoukankan      html  css  js  c++  java
  • c++设计模式之单例模式下的实例自动销毁(垃圾自动回收器)

    关于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 important
    22     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 on
    33             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 }
  • 相关阅读:
    JavaScript字符串转换为变量名
    python对象反射和函数反射
    android studio 更新Gradle版本方法
    【Node.js】'readline' 逐行读取、写入文件内容
    nodejs 设计模式
    MongoError: server instance in invalid state undefined 解决办法
    nodejs对mongodb数据库的增删改查操作(转载)
    JSON详解
    mac 安装python3
    Oracle_安装说明
  • 原文地址:https://www.cnblogs.com/zhengxingpeng/p/6686214.html
Copyright © 2011-2022 走看看