delete this
is valid in C++11
It is valid to call delete this
in a destructor.
The C++ FAQ has an entry about that.
The restrictions of C++11 [basic.life] p5 do not apply to objects under destruction, and C++11 [class.cdtor] does not restrict you from using delete this
.
Despite being valid, it's rarely a good idea. 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.
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.
Note: delete this
may not be used in a destructor as per C++11 [class.dtor] p15, and you have to avoid destroying an object twice.
delete this
used to be undefined behavior in C++03
C++ Standard quote on my claim above (C++03 [basic.life] p5):
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 of POD types, for example), detailed at C++03 [class.cdtor].