C++中delete this
发布日期:2021-10-24 03:36:29 浏览次数:2 分类:技术文章

本文共 1790 字,大约阅读时间需要 5 分钟。

Is it legal (and moral) for a member function to say delete this?  

As long as you’re careful, it’s okay (not evil) for an object to commit suicide (delete this).

Here’s how I define “careful”:

  1. You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by , nor a local object on the stack, nor a namespace-scope / global, nor a member of another object; but by plain ordinary new).
  2. You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.
  3. You must be absolutely 100% positively 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). This includes code that will run in destructors for any objects allocated on the stack that are still alive.
  4. You must be absolutely 100% positively 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 nullptr, 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 .

如果在析构函数中调用delete this,则会陷入死循环:

class TDel{public:    TDel()     {        x = 1;    }    virtual ~TDel()     {        printf("This is Dstr\n");        printf("delete this now\n");        delete this;    }private:    int x;};int main(){    TDel *td = new TDel;    delete td;}

结果如下:

This is Dstrdelete this nowThis is Dstrdelete this nowThis is Dstrdelete this nowThis is Dstrdelete this nowThis is Dstrdelete this now...

 

 

https://isocpp.org/wiki/faq/freestore-mgmt#delete-this

转载于:https://www.cnblogs.com/gqtcgq/p/9411400.html

转载地址:https://blog.csdn.net/weixin_30687587/article/details/94981136 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python newbie——PE No.2
下一篇:Appium+python自动化22-Appium Desktop

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月04日 10时40分19秒