之前讲过了虚函数,其实实现面向对象多态特性的机制。
那多态性里还有重要的一点便是虚析构函数。
接下来看问题重现:
#include <iostream>
using namespace std;
class Cparent
{
public:
Cparent()
{
cout<< "Cparent::constructor is called" <<endl;
}
~Cparent()
{
cout<<"Cparent::destructor is called"<<endl;
}
};
class Cchild: public Cparent
{
char *p;
public:
Cchild()
{
p = new char[20];
cout<<"Cchild::construct is called"<<endl;
}
~Cchild()
{
delete p;
cout<<"Cchild::destructor is called"<<endl;
}
};
int main()
{
Cparent *pParent;
Cchild *pChild = new Cchild();
pParent = pChild;
delete pParent;
return 0;
}
大家能看出这里产生的内存泄漏问题么?
运行结果:
Cparent::constructor is called
Cchild::construct is called
Cparent::destructor is called
看得出我们只调用了父类的析构函数,而并没有调用子类的析构函数,造成子类构造函数里new的内存无法释放。这是因为当pChild指针赋值给pParent后,而编译器由静态联编只调用了父类的构造函数,因此我们需要动态绑定让其调用子类的析构函数,那么就需使用virtual关键字。