让C++对象自杀

今天检测内存泄露,有类似如下代码:

 1 class A
 2 {
 3 public:
 4     A()
 5     {
 6         printf("Create A:\n");
 7     }
 8     ~A()
 9     {
10         printf("Free A:\n");
11     }
12 private:
13     int a;
14 };
15 
16 class B:public A
17 {
18 public:
19     B()
20     {
21         printf("Create B:\n");
22     }
23     ~B()
24     {
25         printf("Free B:\n");
26     }
27 private:
28     int b;
29 };
30 
31 
32 int main(int argc, _TCHAR* argv[])
33 {
34     A* pA = new B;
35     delete pA;
36     getchar();
37     return 0;
38 }

执行的结果是:
Create A:
Create B:
Free A:

很明显出现了内存泄露,只怪自己C++基础不够好!A,B两个类的析构函数使用虚拟函数就可以解决了.但是我想到了一个比较好玩的办法让C++对象自杀.于是有了下面代码

 

View Code
 1 class A
 2 {
 3 public:
 4     A()
 5     {
 6         printf("Create A:\n");
 7     }
 8     ~A()
 9     {
10         printf("Free A:\n");
11     }
12     virtual void KillSelf()
13     {
14         delete this;
15     }
16 private:
17     int a;
18 };
19 
20 class B:public A
21 {
22 public:
23     B()
24     {
25         printf("Create B:\n");
26     }
27     ~B()
28     {
29         printf("Free B:\n");
30     } 
31     virtual void KillSelf()
32     {
33         delete this;
34     }
35 private:
36     int b;
37 };
38 
39 
40 int _tmain(int argc, _TCHAR* argv[])
41 {
42     A* pA = new B;
43     pA->KillSelf();
44     getchar();
45     return 0;
46 }

执行结果如下:

Create A:
Create B:
Free B:
Free A:

泄露解决了~虽然没有直接添加虚拟洗头函数来的好看,就当好玩吧.
以下是一段所有人都关注对象自杀看过的一段文字:

[16.15] Is it legal (and moral) for a member function to say delete this?
 
As long as you're careful, it's OK for an object to commit suicide (delete this).
 
Here's how I define "careful":
 
   1. You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
    2. You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object.
    3. You must be absolutely 100% positive sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
    4. You must be absolutely 100% positive sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.
 
Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.

转载于:https://www.cnblogs.com/baili35/archive/2012/07/31/CppOjbeceKillSelf.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值