使用一个指向基类(析构函数为non-virtual)的指针,来删除一个子类时,会导致为未知行为。这种情况下,基类必须定义虚析构函数。
例如,下面程序会导致未知行为。
//此程序中基类没有定义虚析构函数,会导致异常行为
#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
而下面是gcc 4.8.5的运行结果:
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
做为一个原则, 任何时候只有一个类中拥有虚函数,则应该立即给这个类增加一个虚析构函数(尽管它也许不会做什么)。