Thursday, 27 November 2014

Delete “this” operator works in C++ with examples

How delete “this” operator works in C++:

As we learned earlier the delete operator should works only with the objects that are allocated memory using the operator new. The delete is used to de-allocate the memory.
As of we know the delete operator should not be used for this pointer.
See the below example, to understand how delete works.

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 access because we have deleted this pointer. I.e. any member of the deleted object was not be accessed after deletion.
#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: So the very best practice for the C++ programmer is not do delete this at any time.

No comments: