delete this
is not valid in a destructor. It can be used elsewhere. But it's only rarely a good idea (can't come up with any use-case directly). Doesn't mean i haven't seen it used though. The wxWidgets
framework uses it for their thread class. It has a mode where, when the thread ends execution, it automatically frees system resources and itself (the wxThread object). I found it very annoying, because from outside, you can't know whether it's valid to refer it or not - you can't call a function like IsValid
anymore, because the object doesn't exist. That smells like the main problem with delete this
, apart from the problem that it can't be used for non-dynamic objects. The user of the object should control the lifetime of it, and not the object itself, because it didn't create itself too.
If you do it, make sure you don't touch any data-member, or call any member function anymore on the object you deleted that way. Best do it as the last statement in a non-virtual, protected or private function. Calling delete is valid in a virtual and/or public function too, but i would restrict the visibility of the method doing that.
The C++ FAQ has an entry about that. C++ Standard quote on my claim above (3.8p5
):
Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. [...] If the object will be or was of a class type with a non-trivial destructor, and the pointer is used as the operand of a delete-expression, the program has undefined behavior.
Lifetime ends when the destructor of the object begins execution. Note there are exceptions to the rules coming after that paragraph for objects under construction and destruction (you are allowed to access non-static data members, for example), detailed at 12.7
.