delete this
: a.k.a. how to suicide an object!
Unlike many other said, according to the C++ specification calling
delete this
is not illegal: it simply requires to know what does it mean.
In your case the infinite loop in not due to the
delete this
inside
f()
but
to the delete this
into the destructor.
Calling
delete
on a pointer actually means do two things:
- call the destructor and ...
- call the
operator delete(void*)
function, whose default provided implementation actually gives the memory back to the system.
Now, since
this
is a pointer,
delete this
has an implicit call to the destructor itself, hence destructors should never call
delete this
(since you're asking to destroying something is already been destroyed so you destroy it over and over)
About calling
delete this
into
f()
(or whatever other function not called by the destructor) this can be accomplished, but requires some cares:
- You must be sure that the object is dynamically allocated: if someone has
{
Str a;
a.f();
}
will destroy
a
that is then automatically re-detroyed at the end of the block (double destruction is technically "
undefined behavior", so anything can happen).
- You must ensure that the body of
f()
will not refer to any
Str
member variables, or virtual functions, or member function referring member variables, after
delete this
is called. This is the consequence of the fact that delete destroys the object hence no members exist anymore after that.
- You must ensure no one actually still refer the object you deleted. This is not different than the ususal problem of dangling pointers, but with the fact that who calls
f()
may be is not expecting an object suicide.
Putting all those requirements together ends up in a situation where you expose an interface (the
f()
funcntion) having requirements about code you cannot control (what calls f() may be anything, being f() itself public).
So, unless you are in very particular cases, avoid that practice at all. Also for the very simple reason that the most of the programmers will not expect it and understand it.