【C++】Virtual 析构函数

  使用指向具有非virtual 析构函数 的基类的指针来删除派生类对象会导致未定义的行为。为了纠正这种情况,应该用 virtual 析构函数来定义基类。例如,以下程序导致未定义行为。


// CPP program without virtual destructor  
// causing undefined behavior 
#include<iostream> 
  
using namespace std; 
  
class base { 
  public: 
    base()      
    { cout<<"Constructing base \n"; } 
    ~base() 
    { cout<<"Destructing base \n"; }      
}; 
  
class derived: public base { 
  public: 
    derived()      
    { cout<<"Constructing derived \n"; } 
    ~derived() 
    { cout<<"Destructing derived \n"; } 
}; 
  
int main(void) 
{ 
  derived *d = new derived();   
  base *b = d; 
  delete b; 
  getchar(); 
  return 0; 
} 

输出结果:

Constructing base
Constructing derived
Destructing base

 

  使基类析构函数virtual 保证派生类的对象被正确地析构。同时调用基类和派生类destructor。例如,

// A program with virtual destructor 
#include<iostream> 
  
using namespace std; 
  
class base { 
  public: 
    base()      
    { cout<<"Constructing base \n"; } 
    virtual ~base() 
    { cout<<"Destructing base \n"; }      
}; 
  
class derived: public base { 
  public: 
    derived()      
    { cout<<"Constructing derived \n"; } 
    ~derived() 
    { cout<<"Destructing derived \n"; } 
}; 
  
int main(void) 
{ 
  derived *d = new derived();   
  base *b = d; 
  delete b; 
  getchar(); 
  return 0; 
} 

输出结果:

Constructing base
Constructing derived
Destructing derived
Destructing base

  作为一个指导原则,任何时候在类中都有一个virtual函数,您应该立即添加一个virtual析构函数(即使它什么也不做)。这样,你就可以确保以后不会有任何意外。

 

文章出处:

  www.geeksforgeeks.org

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值