May 20, 2010

Null Pointers and Delete in C++

From here: Null Pointers and Delete C++ guarantees that delete operator checks its argument for null-ness. If the argument is 0, the delete expression has no effect. In other words, deleting a null pointer is a safe (yet useless) operation.
 
if (ptr == NULL) // useless, delete already checks for null value
{
  delete(ptr);
}
// but always set ptr = NULL after deleting it otherwise another 
// call to delete(ptr) will throw an exception
ptr = NULL; 

No comments: