: a.k.a. how to suicide an object!
Unlike many other said, according to the C++ specification calling
is not illegal: it simply requires to know what does it mean.
In your case the infinite loop in not due to the
but to the
delete this into the destructor
on a pointer actually means do two things:
- call the destructor and ...
- call the
function, whose default provided implementation actually gives the memory back to the system.
is a pointer,
has an implicit call to the destructor itself, hence destructors should never call
(since you're asking to destroying something is already been destroyed so you destroy it over and over)
(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
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
will not refer to any
member variables, or virtual functions, or member function referring member variables, after
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
may be is not expecting an object suicide.
Putting all those requirements together ends up in a situation where you expose an interface (the
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.