Sunday, 3 July 2011

to use or not to use "delete this"

Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.
1) delete operator works only for objects allocated using operator new. If the object is created using new, then we can do delete this, otherwise behavior is undefined.
class A
{
  public:
    void fun()
    {
        delete this;
    }
};
int main()
{
  /* Valid */
  A *ptr = new A;
  ptr->fun();
  ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr.
  /* Invalid: Undefined Behavior */
  A a;
  a.fun();
  getchar();
  return 0;
}
2) Once delete this is done, any member of the deleted object should not be accessed after deletion.
#include<iostream>
using namespace std;
class A
{
  int x;
  public:
    A() { x = 0;}
    void fun() {
      delete this;
      /* Invalid: Undefined Behavior */
      cout<<x;
    }
};


https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this

Identical Linked lists

Two linked lists are said to be identical if they have the same date in the same order.
Eg: list A = 2->7->44 and  list B = 2->7->44 are said to be identical.

A simple iterative solution for finding out if the lists are identical.

int isIdentical(list a, list b)
{
     for(; a && b && a->data == b->data; a = a->next, b = b->next);
     return !(a || b);
}