关于delete this的问题

今天在学习如何控制函数只在堆上或者只在栈上创建函数的时候碰巧碰到了这个问题,现象之前自己写程序的时候也遇到过这样的问题,只是直接写了delete this并没有去深入的探讨背后的问题。

       使用delete关键字在销毁对象的时候会调用对象的析构函数,而delete语句又包括在析构函数之内,这样为什么不会形成死锁?delete之后怎么防止访问非法内存?

       下面是isocpp针对这个问题的回答: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.

大意就是:

  1. 确定该对象是由new关键字分配的
  2. 确保运行delete new的是最后一个使用this指针的成员函数
  3. 确保在delete this运行之后的其他成员函数(包括在析构函数内用于处理栈上分配内存的代码),不会使用this对象
  4. 确保不会使用this指针(包括对它进行检查、比较等操作)

在应用于this指针指向基类(base class)但是有没有虚析构函数(virtual destructor)的情况下通常会有警告。

BTW,这也是为什么在有继承的情况下,析构函数通常是虚函数

转载于:https://my.oschina.net/u/3193939/blog/3020043

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值