Rule Definition
'delete this' leaves the current instance in a "dangling" state, which may lead to undefined behavior. 'delete this' is only valid if you can guarantee that the instance members will no longer be accessed. Furthermore, 'delete this' is only valid if you can guarantee the object was allocated using the 'new' operator.
There are acceptable patterns of code where delete this is used. For instance, when a class is always dynamically allocated, only referenced by a manager, and unregisters itself from the manager on destruction. It is possible for an instance of the class to "commit suicide" by using 'delete this' when it discovers it is no longer needed. However this pattern and its implication are usually not well understood, and other solutions are preferred.
Remediation
The simplest solution is not to use 'delete this' at all. Objects allocated on the stack have their destructors invoked when the object goes out of scope.
Violation Code Sample
class SomeClass
{
public:
void doSomething();
void destroy();
// ...
};
void SomeClass::destroy()
{
delete this; // Dangerous!!
}
// ...
SomeClass sc;
// ...
sc.destroy(); // Undefined behavior
Reference
"CERT: Avoid deleting this":https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this
Related Technologies
C++
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.