The delete operator should work only with the objects that are allocated memory using the operator new. The delete is used to de-allocate the memory.
The delete operator should not be used for this pointer.
See the below example, to understand how delete works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class MyEXClass { public: MyEXClass () { }; ~MyEXClass () { }; void MyFun() { delete this; } }; int main() { /* Following is Valid */ MyEXClass *ptrCls = new MyEXClass; ptrCls->MyFun (); ptrCls = NULL; // make ptr NULL to make sure that things are not accessed using ptr. /* And following is Invalid: Undefined Behavior */ MyEXClass ocCls; ocCls.MyFun(); getchar(); return 0; } |
2) See the below example we have used delete this, after deleting this we are trying to access the member of the class, which is not accessible because we have deleted this pointer. i.e. any member of the deleted object was not be accessed after deletion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include<iostream> using namespace std; class MyEXClass { int iVal; public: MyEXClass () { iVal = 10; }; ~MyEXClass () { }; void MyFun() { delete this; } void MyFun2 () { cout << iVal << endl; } }; int main() { /* Following is Valid */ MyEXClass *ptrCls = new MyEXClass; ptrCls->MyFun (); ptrCls->MyFun2 (); ptrCls = NULL; // make ptr NULL to make sure that things are not accessed using ptr. /* And following is Invalid: Undefined Behavior */ MyEXClass ocCls; ocCls.MyFun(); getchar(); return 0; } |
NOTE: The very best practice for the C++ programmer is not do delete this at any time.