使用具有非虚拟析构函数的基类类型的指针删除派生类对象会导致未定义的行为。要纠正这种情况,应使用虚拟析构函数定义基类。例如,遵循程序会导致未定义的行为。
// CPP program without virtual destructor
// causing undefined behavior
#include
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;
}
尽管以下程序的输出在不同的编译器上可能会有所不同,但是当使用Dev-CPP进行编译时,它将输出以下内容:
Constructing base
Constructing derived
Destructing base
将基类析构函数设为虚拟可确保派生类的对象被正确地析构,即,基类和派生类的析构函数都将被调用。例如,
// A program with virtual destructor
#include
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
原则上,任何时候在类中具有虚函数时,都应立即添加虚析构函数(即使它不执行任何操作)。这样,您可以确保以后不会出现任何意外情况。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。