使用指向具有非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析构函数(即使它什么也不做)。这样,你就可以确保以后不会有任何意外。
文章出处: