C++ virtual 析构函数

  • case 1
#include <iostream>
using namespace std;
 
class Base{
  public:
    ~Base() {cout<<"~B"<<endl;}
};
 
class Derived:public Base{
  public:
    ~Derived() {cout<<"~D"<<endl;}
};
 
int main (){
  Base *b = new Derived; //注意这里
  delete b;
}

子类指向父类,查看打印日志:

~B

可见删除子类指向父类的指针,代表delete只删除了父类,并没有删除子类的相关内存,会产生内存泄漏。所以在多态的使用过程中,delete(指向父类的子类对象)需要格外注意是否会没有释放子类或者父类。

  • case 2
#include <iostream>
using namespace std;
 
class Base{
  public:
    ~Base() {cout<<"~B"<<endl;}
};
 
class Derived:public Base{
  public:
    ~Derived() {cout<<"~D"<<endl;}
};
 
int main (){
  Derived *d = new Derived; //注意这里
  delete d;
}

子类指向子类指针,查看打印日志:

~D

~B

可以得知,delete子类的析构顺序:是先释放子类,在释放父类。

这是我们期望的结果,所以没啥问题。。。

  • case 3

对于case 1当中的情况,如何去规避呢?  需要将父类的析构函数定义为virtual

#include <iostream>
using namespace std;
 
class Base{
  public:
    virtual ~Base() {cout<<"~B"<<endl;}
};
 
class Derived:public Base{
  public:
    ~Derived() {cout<<"~D"<<endl;}
};
 
int main (){
  Base *d = new Derived; //注意这里
  delete d;
}

打印结果:

~D

~B

原理:delete d; //d虽然为Base*,但是它的析构函数是virtual的,所以它调用析构函数,其实是调用虚函数表中的函数。而Base* d指向的虚函数表在内存中其实是new Derived类的虚函数表。所以通过Base类的virtual函数 + Base* d指向派生类(Derived)对象,从而使得在调用delete d的时候实际上是调用的是delete Derived* d的意思,也就是第二种情况的效果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值