zoukankan      html  css  js  c++  java
  • c++ 虚析构函数[避免内存泄漏]

    c++  虚析构函数:

    虚析构函数
    (1)虚析构函数即:定义声明析构函数前加virtual 修饰, 如果将基类的析构函数声明为虚析构函数时,
    由该基类所派生的所有派生类的析构函数也都自动成为虚析构函数。

    (2)基类指针pbase 指向用new动态创建的派生类对象child时,用“delete pbase;”删除对象分两种情况:
    第一,如果基类中的析构函数为虚析构函数,则会先删除派生类对象,再删除基类对象
    第二,如果基类中的析构函数为非虚析构函数,则只会删除基类对象,不会删除派生类对象,这样便出现了内存泄漏了

    #include <iostream>
    using namespace std;
    #include <string>
    //////////////////////////// 
    class Base {
    public:
    
    #if  0
        virtual ~Base();// in Child::~Child()    in Base::~Base()
    #else
         ~Base();        // in Base::~Base() 存在内存泄漏的危险
    #endif
    };
    
    Base::~Base()
    {
        cout<<"in Base::~Base()"<<endl;
    }
    ////////////////////////////
    
    class Child: public Base {
    public:
        ~Child();
    };
    
    Child::~Child()
    {
        cout<<"in Child::~Child()"<<endl;
    }
    
    int demo()
    {
        Base *pc = new Child;
        cout<<"-----------"<<endl;
        delete pc;
        cout<<"-----------"<<endl;
        return 0 ;
    }
    
    int main() {
        demo();
        while(1);
        return 0;
    }
  • 相关阅读:
    搭建本地yum仓库
    linux下查看http 并发和 tcp连接数
    MySQL用户管理及SQL语句详解
    API开发之接口安全(一)----生成sign
    TP5使用API时不可预知的内部异常
    TP5通用化API接口数据封装
    根据指定日期获取近一周,及该月起止时间戳
    14-Promise
    4-字符串扩展与新增方法
    换行
  • 原文地址:https://www.cnblogs.com/mylinux/p/4095418.html
Copyright © 2011-2022 走看看