有时候我们需要用基类的指针删除其子类的对象,这时候要非常注意,倘若基类的析构函数是 non-virtual析构函数,那么事实上,只有基类的析构函数被调用,派生类的析构函数并没有被调用,这可能会导致资源泄漏。为避免这中情况发生,我们可以将基类的析构函数声明为virtual,这样的话,子类对象才能被完全销毁.
-
#include <iostream>
-
#include <stdlib.h>
-
#include <crtdbg.h>
-
-
#ifdef _DEBUG
-
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
-
#endif
-
-
using namespace std;
-
-
class BaseClass
-
{
-
public:
-
virtual ~BaseClass() = 0;
-
//~BaseClass();
-
};
-
-
BaseClass::~BaseClass()
-
{
-
cout << "the ~BaseClass is called" << endl;
-
}
-
-
class DerivedClass : public BaseClass
-
{
-
public:
-
DerivedClass(int x, int y)
-
:X(x)
-
,Y(y)
-
{
-
a = new int[y];
-
}
-
-
~DerivedClass()
-
{
-
cout << "the ~Derivedclass is called" << endl;
-
if(a)
-
{
-
delete a;
-
a = NULL;
-
}
-
}
-
-
-
private:
-
int X;
-
int Y;
-
int *a;
-
};
-
-
void main()
-
{
-
//memory check
-
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
-
-
BaseClass *bs= new DerivedClass(2, 3);
-
-
delete bs;
-
-
system("pause");
-
- }
程序运行结果为
the ~Derivedclass is called
the ~BaseClass is called
基类和派生类的析构函数都被调用
倘若基类的析构函数为~BaseClass();即 non-virtual 析构函数,
程序运行结果为
the ~BaseClass is called,
只有基类的析构函数被调用,子类中指针 a 指向的内存并没有被释放
Dumping objects ->
e:\work\test\test\test.cpp(287) : {128} normal block at 0x00395E38, 12 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
12 字节的内存泄漏了