Suppose you had a class with a member function erase() that called delete this;:
// Delete_class.h #pragma once class Delete_class; class Delete_class { public: Delete_class( int n = 0.0 ); void erase(); private: int datum; };
// Delete_class.cpp #include <iostream> #include "Delete_class.h" Delete_class::Delete_class( int n ): datum( n ) { // Empty constructor } void Delete_class::erase() { delete this; }
If you compile and execute this program:
#include "Delete_class.h" int main(); int main() { Delete_class *p_info= new Delete_class{42}; p_info->erase(); return 0; }
everything appears to function correctly. Indeed, everything will function correctly, for the memory for the object was allocated dynamically, and p_info is simply storing the address of that memory that allocated by the operating system. Consequently, when you call erase(), this is simply assigned that memory location, so when delete this; is called, it indicates to the operating system that the memory at that location is no longer required. If no subsequent access is made to anything associated with the object, there should be no further issues.
The requirements for being able to call delete this; include:
Unfortunately, there is no way that the constructor can be made aware as to whether or not the object on which the constructor is being called is through dynamic or static memory allocation. Thus, this can really only be used if the programmer is guaranteed that the objects will always be dynamically allocated; for example, as nodes in a linked list or a tree.