在C++的基类中,析构函数为什么声明为虚函数,如果不声明为虚函数时,会发生什么?代码奉上:
#include <iostream>
class Base
{
public:
Base() {
std::cout << "Base::Create" << std::endl;
}
~Base() {
std::cout << "Base::Destory" << std::endl;
}
};
class Derive :public Base
{
public:
Derive() {
std::cout << "Derive::Create" << std::endl;
std::cout << "Derive::malloc memory" << std::endl;
}
~Derive() {
// 通常在析构函数中进行资源的释放工作
std::cout << "Derive::free memory" << std::endl;
std::cout << "Derive::Destory" << std::endl;
}
};
int main(int argc, _TCHAR* argv[])
{
Base* p = new Derive();
// do something
delete p;
return 0;
}
执行结果:
Base::Create
Derive::Create
Derive::malloc memory
Base::Destory
请按任意键继续. . .
从上面的输出结果中看出,派生类中的析构函数没有进行调用。如果在派生类中申请了资源,在释放的时候(假设派生类的资源在析构函数中回收),可能会造成内存和资源的泄漏。这就是在基类中为什么析构函数一般为虚函数的原因。具体原因,当删除基类指针指向的派生类时,如果基类的析构函数不为虚函数的时候,不会触发动态绑定,所以不会调用派生类的析构函数。
如果将基类中的析构函数声明为虚函数时:
class Base
{
public:
Base() {
std::cout << "Base::Create" << std::endl;
}
virtual ~Base() {
std::cout << "Base::Destory" << std::endl;
}
};
执行结果:Base::Create
Derive::Create
Derive::malloc memory
Derive::free memory
Derive::Destory
Base::Destory
请按任意键继续. . .
OK