這是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會再次觸發析構函數,造成無限遞歸。