Dangling Pointers after Destructor is called

After an object is destroyed, it ceases to exist. There is no point in setting its members to particular values when those values will immediately cease to exist.

The pattern of setting pointers to NULL when deleteing the objects they point to is actively harmful and has caused errors in the past. Unless there’s a specific reason the pointer needs to be set to NULL (for example, it is likely to be tested against NULL later) it should not be set to NULL.

Consider:

Foo* foo getFoo();
if (foo!=NULL)
{
    do_stuff();
    delete foo;
}
// lots more code
return (foo == NULL);

Now, imagine if someone adds foo = NULL; after the delete foo; in this code, thinking that you’re supposed to do that. Now the code will give the wrong return value.

Next, consider this:

Foo* foo getFoo();
Foo* bar = null;
if (foo != NULL)
{
    bar = foo;
    do_stuff(bar);
    delete bar;
    bar = NULL;
}
// lots more code
delete foo;

We always set pointers to NULL after we delete them, so this delete foo; must be safe, right? Clearly it’s not. So setting pointers to NULL after you delete them is neither necessary nor sufficient.

Don’t do it.

Leave a Comment