目录
- 由于类的多态性,基类指针可以指向派生类的对象,如果删除该基类的指针,就会调用该指针指向的派生类析构函数,而派生类的析构函数又自动调用基类的析构函数,这样整个派生类的对象完全被释放。
- 如果析构函数不被声明成虚函数,则编译器实施静态绑定,在删除基类指针时,只会调用基类的析构函数而不调用派生类析构函数,这样就会造成派生类对象析构不完全,造成内存泄漏。
- 所以将析构函数声明为虚函数是十分必要的。在实现多态时,当用基类操作派生类,在析构时防止只析构基类而不析构派生类的状况发生,要将基类的析构函数声明为虚函数。
析构函数不是虚函数:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "父类构造函数" << endl;
}
~Parent()
{
cout << "父类析构函数" << endl;
}
};
class Son : public Parent
{
public:
Son()
{
cout << "子类构造函数" << endl;
}
~Son()
{
cout << "子类析构函数" << endl;
}
};
int main()
{
Parent *p = new Son();
delete p;
p = nullptr;
return 0;
}
执行结果:
析构函数是虚函数:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "父类构造函数" << endl;
}
virtual ~Parent()
{
cout << "父类析构函数" << endl;
}
};
class Son : public Parent
{
public:
Son()
{
cout << "子类构造函数" << endl;
}
~Son()
{
cout << "子类析构函数" << endl;
}
};
int main()
{
Parent *p = new Son();
delete p;
p = nullptr;
return 0;
}
执行结果: