C++中delete this

本文探讨了C++中成员函数使用delete this的安全性和道德性问题,并详细定义了确保此操作安全所需的条件。同时,文章通过一个具体示例说明了在析构函数中调用delete this可能导致的死循环问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 placement new, 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 virtual destructor.

如果在析构函数中调用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 Dstr
delete this now
This is Dstr
delete this now
This is Dstr
delete this now
This is Dstr
delete this now
This is Dstr
delete this now
...

 

 

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值