这是C++标准基金会(isocpp)的答案:来源https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
Is it legal (and moral) for a member function to say
As long as you’re careful, it’s okay (not evil) for an object to commit suicide (?
delete this
delete
this
).
Here’s how I define “careful”:
Naturally the usual caveats apply in cases where your
- You must be absolutely 100% positively sure that
object was allocated via
this
(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
).
new
- You must be absolutely 100% positively sure that your member function will be the last member function invoked on
object.
this
- You must be absolutely 100% positively sure that the rest of your member function (after the
delete
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.
this
- You must be absolutely 100% positively sure that no one even touches the
pointer itself after the
this
delete
line. In other words, you must not examine it, compare it with another pointer, compare it with
this
, print it, cast it, do anything with it.
nullptr
pointer is a pointer to a base class when you don’t have a virtual destructor.
this
翻译如下:
只要你足够“小心”,delete this 就是合法的。
所谓小心:
1)this指向的实例必须是new出来的,不能是new[] 出来的,也不能是栈上的,也不是全局变量......只能是简单的new出来的;
2)这个调用了delete this 的成员函数(下面称为当事函数)返回后,同实例下的其他成员函数不得再被调用(这好理解,因为实例不存在了);
3)当事的成员函数调用了delete this之后,不得再调用this的任何成员函数和成员变量(这好理解,理由同2);
4)当事函数调用了delete this之后,不得以任何形式提及this,包括比较、打印、类型转换等(因为this已经不存在了)。
最后一句不太明白,讲了什么虚析构函数,有明白人解释下吗?
补充一句,网上很多人都谈到了,不能在析构函数中调用delete this,因为delete this会再次触发析构函数,造成无限递归。