将 析构函数 声明为 虚函数 的必要性

大家看这个例子:


#include<iostream>
using namespace std;

class Base
{
public:
    Base();
   ~Base();
};
Base::Base()
{
    cout << "Base is create" << endl;
}
Base::~Base()
{
    cout << "~Base is destructor...." << endl;
}

class Derived :public Base
{
public:
    Derived();
    ~Derived();

private:
    int *p;
};

Derived::Derived()
{
    p = new int(5);
    cout << "Derived is create" << endl;
}

Derived::~Derived()
{
    delete p;
    cout << "~Derived is destructor....." << endl;
}

int main(void)
{
    Base *b = new Derived();
    delete b;
}

运行结果:
这里写图片描述
这说明。通过基类指针删除派生类的对象时调用的是基类的析构函数,派生类的析构函数没有执行,因此派生类的对象中动态分配的内存空间没有得到释放,造成了内存泄露。也就是说派生类对象成员p所指的内存空间,在对象消失后不能被本程序继续使用,但同时也没有释放。对于内存需求量较大,长期连续运行的程序来说,这样的错误是非常危险的,最终导致因内存不足而引起程序终止。

这里写图片描述
上如中,程序已经运行完了,但是5还存在于内存中。

解决这个问题的有效方法就是将析构函数声明为虚函数。


class Base
{
public:
    Base();
    virtual ~Base();
};

这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值