让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++对象自杀.于是有了下面代码

让C++对象自杀让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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/57431

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午8:15
下一篇 2023年2月9日 上午8:15

相关推荐