C++虚函数(5) - 虚析构函数

来源:互联网 发布:河南科技大学软件 编辑:程序博客网 时间:2024/05/08 23:13

使用一个指向基类(定义了一个non-virtual析构函数)的指针,来删除一个子类时,会导致未知行为。这种情况下,基类必须定义虚析构函数。
Source: https://www.securecoding.cert.org/confluence/display/cplusplus/OOP34-CPP.+Ensure+the+proper+destructor+is+called+for+polymorphic+objects

例如,下面程序会导致未知行为。

//此程序中基类没有定义虚析构函数,会导致异常行为#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;  return 0;}
不同的编译器可能会打印不同结果。下面是visual studio 2015的结果:

Constructing base
Constructing derived
Destructing base


将基类的析构函数定义为virtual后, 就可以确保子类能被正确的析构了。
参考下面例子:

// 使用虚析构函数的例子程序#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;  return 0;}
输出:

Constructing base
Constructing derived
Destructing derived
Destructing base

做为一个原则, 任何时候只有一个类中拥有虚函数,则应该立即给这个类增加一个虚析构函数(尽管它也许不会做什么)。

0 0
原创粉丝点击