内存泄露之局部销毁

#include <iostream>
using namespace std;

#define DECLARE_SAFE_RELEASE() virtual void Release() { delete this; }
#define SAFE_RELEASE(p) { if (NULL != p) { (p)->Release(); (p)=NULL; } }

class A
{
public:
A() { pA = new int(10); cout << *pA << endl; }
virtual ~A() { delete pA; cout << "pA is delete" << endl; }
DECLARE_SAFE_RELEASE()

private:
int * pA;
};

class B : public A
{
public:
B() { pB = new int(20); cout << *pB << endl; }
~B() { delete pB; cout << "pB is delete" << endl; }

private:
int * pB;
};

class C : public B
{
public:
C() { pC = new int(30); cout << *pC << endl; }
~C() { delete pC; cout << "pC is delete" << endl; }

private:
int * pC;
};

int main()
{
A * p = new C;
cout << "-----------------------------------" << endl;
SAFE_RELEASE(p)

cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;

return 0;
}

结果:

小结:

1.内存泄露之局部销毁解决方法。
2.父类的析构函数是虚函数,其子类,子类的子类的析构函数也是虚函数
3.代价:类的大小会增加,1个int型的体积
posted @ 2012-03-08 20:46  木愚  阅读(249)  评论(0编辑  收藏  举报