转自:https://blog.youkuaiyun.com/qiurisuixiang/article/details/6926313
先来看一段代码:
-
//test.cpp
-
#include <iostream>
-
using namespace std;
-
class father
-
{
-
public:
-
father()
-
{
-
mPtr = new int;
-
}
-
~father()
-
{
-
delete mPtr;
-
cout << "father Destruction......" << endl;
-
}
-
private:
-
int *mPtr;
-
};
-
class son:public father
-
{
-
public:
-
son()
-
{
-
mStr = new long;
-
}
-
~son()
-
{
-
delete mStr;
-
cout << "son Destruction......" << endl;
-
}
-
private:
-
long *mStr;
-
};
-
int main()
-
{
-
father *p = new son;
-
delete p;
-
return 0;
-
}
程序运行截图:
从程序的运行结果来看,程序最后只释放了父类的内存,子类的内存并没有释放。则这段程序产生了内存泄露。那是什么原因导致的呢?
在main函数中new出来的是子类son的对象,采用一个父类father的指针来接收,故在析构的时候,编译器因为只知道这个指针是父类的,所以只将父类部分的内存析构了,而不会去析构子类的内存,就造成了内存泄露,那么如何避免这种情况的产生呢?
将父类的析构函数改为虚函数,就可以避免这种情况。
-
//test.cpp
-
#include <iostream>
-
using namespace std;
-
class father
-
{
-
public:
-
father()
-
{
-
mPtr = new int;
-
}
-
virtual~father()
-
{
-
delete mPtr;
-
cout << "father Destruction......" << endl;
-
}
-
private:
-
int *mPtr;
-
};
-
class son:public father
-
{
-
public:
-
son()
-
{
-
mStr = new long;
-
}
-
~son()
-
{
-
delete mStr;
-
cout << "son Destruction......" << endl;
-
}
-
private:
-
long *mStr;
-
};
-
int main()
-
{
-
father *p = new son;
-
delete p;
-
return 0;
-
}
程序运行截图:
从程序的运行结果可以看出,父类和子类的内存都被析构了。所以在使用多态时一定要将父类的析构函数定义成虚函数,从而避免内存泄露。