pointer quiz

One of my pet peeves with regards to C++ is how very few people understand how the delete operator handles NULL pointers. Let's see if you pass the test!

Question: What happens when you do this:


myType *ptr = NULL;
delete ptr;



Well? Your choices are:

a) Crash, bang, boom, your computer is now a very heavy paperweight.
b) Nothing - the delete line ignores the ptr to be deleted.


It turns out that deleting a null pointer is safe. Section 5.3.5/2 of the C++ standard states that:

"In either alternative, if the value of the operand of delete is the
null pointer the operation has no effect."


This has been a pet peeve of mine for a while now. I can't count the number of times I've seen programmers write something like this in class destructors or cleanup methods:


if (pMyPtr)
delete pMyPtr;


This is stupid for several reasons. For a start, the if statement is redundant - if the pointer is NULL the delete will do nothing. Secondly, the programmer never sets the pointer to NULL after deleting it, which means that if this code were to be called again, you would definitely experience problems.

In order to avoid these issues, and avoid angering me if I ever see your code, you should:

  1. Always initialize pointers to NULL if you're not going to set them to something else straight away (i.e.- if the pointer is not always used).

  2. Always set them to NULL after you delete them, especially if there's a chance that the delete can be called twice.