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 a object to commit suicide ( delete this ).
Here's how I define "careful":
- You must is absolutely 100% positively sure
this that object is allocated via new (not new[] by, nor by placement , nor a local object on the stack, nor a namespace-scope/global, nor a member of another object; But by plain ordinary new ).
- You must is absolutely 100% positively sure that your member function would be the last member function invoked on
this OB Ject.
- You must is absolutely 100% positively sure that the rest of your member function (after the line
delete this ) doesn ' t tou Ch any piece of the this object (including calling any and member functions or touching any data members). This includes code that would run in destructors for any objects allocated on the stack that is still alive.
- You must is absolutely 100% positively sure that is no one even touches the pointer itself after the line
this delete this . In other words, your must not examine it, compare it with another pointer, compare it with nullptr , print it, cast it, does any thing with it.
Naturally the usual caveats apply in cases where your this pointer are a pointer to a base class when you don ' t have a vir Tual destructor.
If you call delete this in a destructor, you are stuck in a dead loop:
classtdel{ Public: TDel () {x=1; } Virtual~TDel () {printf ("This is dstr\n"); printf ("Delete this now\n"); Delete This; }Private: intx;};intMain () {TDel*TD =NewTDel; DeleteTD;}
The results are as follows:
This isDstrDelete ThisNowThis isDstrDelete ThisNowThis isDstrDelete ThisNowThis isDstrDelete ThisNowThis isDstrDelete This Now ...
Https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
Delete this in C + +