Wow, "delete this;"... I can't begin to tell you how unsafe this is.
>>is such a method recommended?
Here is my scale in C++:
- Desirable (includes things like RAII, exception-safety, binary compatibility, generic implementations, concept checking, const-correctness, etc.)
- Recommended (includes things like programming-by-contract, independence, abstraction, encapsulation, non-copyable, smart pointers, etc.)
- Acceptable (includes things like the visitor pattern, dynamic casts, etc.)
- Lesser evil (includes things like singleton patterns, fly-weight idiom, union-types, raw-pointers, etc.)
- Last resort (includes very few things that are horrible, like const-casts and C-style casts, for example)
- Forbidden, horrible, disgusting, evil code (includes almost nothing, but it includes "delete this;")
What if your object is allocated statically (not with new)?
What if your object is allocated as part of an array?
What if there exists another pointer to your object?
...
These are all perfectly normal uses of a class in C++. And they would all lead to a disaster if you decide to do a "delete this;" statement. The const_cast and setting this to null is completely useless. You have contrived an example in which this works, but that's just a very special case. In most cases, the this pointer won't relate to anything meaningful in the caller's code (in a method, the this pointer should always be treated as a read-only local variable, there is no guarantee that treating it any differently will be valid).
If you …