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;
    }
  • 相关阅读:
    delphi private public protected
    delphi 程序流程控制
    TTrayIcon-Delphi系统托盘组件
    如果没有你-莫文蔚
    ShellExecute 调用bat文件
    delphi ShellExecute使用
    delphi 测试ping
    centos7 安装redis
    my.cnf 基础配置
    Delphi的类和对象(七)- 继承
  • 原文地址:https://www.cnblogs.com/mylinux/p/4095418.html
Copyright © 2011-2022 走看看