大家看这个例子:
#include<iostream>
using namespace std;
class Base
{
public:
Base();
~Base();
};
Base::Base()
{
cout << "Base is create" << endl;
}
Base::~Base()
{
cout << "~Base is destructor...." << endl;
}
class Derived :public Base
{
public:
Derived();
~Derived();
private:
int *p;
};
Derived::Derived()
{
p = new int(5);
cout << "Derived is create" << endl;
}
Derived::~Derived()
{
delete p;
cout << "~Derived is destructor....." << endl;
}
int main(void)
{
Base *b = new Derived();
delete b;
}
运行结果:
这说明。通过基类指针删除派生类的对象时调用的是基类的析构函数,派生类的析构函数没有执行,因此派生类的对象中动态分配的内存空间没有得到释放,造成了内存泄露。也就是说派生类对象成员p所指的内存空间,在对象消失后不能被本程序继续使用,但同时也没有释放。对于内存需求量较大,长期连续运行的程序来说,这样的错误是非常危险的,最终导致因内存不足而引起程序终止。
上如中,程序已经运行完了,但是5还存在于内存中。
解决这个问题的有效方法就是将析构函数声明为虚函数。
class Base
{
public:
Base();
virtual ~Base();
};