c++ 虚析构函数[避免内存泄漏]

China☆狼群 提交于 2019-12-07 07:19:19

 

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;
}

 

转载于:https://www.cnblogs.com/mylinux/p/4095418.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!