c/c++整理--析构函数

c++中虚析构函数的作用是什么?

  析构函数是为了在对象不被使用后释放它的资源,虚函数是为了实现多态。那么,把析构函数声明为virtual有什么作用呢? 请看下面代码:


<span style="font-size:18px;">#include <iostream>  
  
using namespace std;  
  
class Base  
{  
public:  
    Base(){ }           //Base的构造函数  
    ~Base()             //Base的析构函数  
    {  
        cout<<"output from the destructor of class Base"<<endl;  
    }  
    virtual void Dosomething()  
    {  
        cout<<"do something in class Base"<<endl;  
    }     
};  
  
class Derived : public Base  
{  
public:  
    Derived(){ }        //Derived的构造函数  
    ~Derived()          //Derived的析构函数  
    {  
        cout<<"output from the destructor of class Derived"<<endl;  
    }  
    void Dosomething()  
    {  
        cout<<"do something in class Derived"<<endl;  
    }  
};  
  
int main()  
{  
    Derived *pt1 = new Derived();  
    pt1->Dosomething();  
    delete pt1;  
      
    Base *pt2 = new Derived();  
    pt2->Dosomething();  
    delete pt2;  
      
    return 0;  
}</span

程序输出:

<span style="font-size:18px;">do something in class Derived  
output from the destructor of class Derived  
output from the destructor of class Base  
do something in class Derived  
output from the destructor of class Base</span>
代码37行可以正常释放pt1的资源,但是代码41行并没有正常释放pt2的资源,从结果看,Derived类的析构函数并没有被调用。通常情况下,类的析构函数里面都是释放内存资源,而析构函数不被调用的话就会造成内存泄漏。原因是指针pt2是Base类型的指针,释放pt2时只进行Base类的析构函数。在代码第9行加上virtual关键字后
    do something in class Derived  
    output from the destructor of class Derived  
    output from the destructor of class Base  
    do something in class Derived  
    output from the destructor of class Derived  
    output from the destructor of class Base  

此时释放指针pt2时,由于Base的析构函数是virtual的,就会先找到并执行Derived类的析构函数,然后执行Base类的析构函数,资源正常释放,避免了内存泄漏。

  因此,只有当一个类被用来作为基类的时候,才会把析构函数写成虚析构函数。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值