views:

121

answers:

3

Possible Duplicate:
Why doesn't delete set the pointer to NULL?

Is there any purpose for a pointer to deallocated memory?

+3  A: 

C++ does exactly what you tell it to do. You didn't set the pointer to null, you deleted the memory that the pointer is pointing to.

Why would you waste the extra step of setting it to null (for performance reasons), if you didn't need to?

Starkey
A: 

No, there's no real use to leaving it set to the original value, other than showing how inept people are at writing code :-)

It follows the traditions of C in that you're expected to know what you're doing. The cost of having the compiler set freed pointers to NULL was deemed too high in the C days and this has carried over to C++ with delete. If you code properly, then having the compiler set the pointer to NULL is a waste, since you'll either set it to something else or not use it again.

If you really want to make your code safer, you'd do something like (in C):

void myFree (void **pMem) {
    free (**pMem);
    *pMem = NULL;
}
myFree (&x);

instead of just:

free (x);

But, if you're going to go to that level (and introduce such an abomination), just switch to Java and be done with it, then you don't have to concern yourself with manual memory management at all.

paxdiablo
Or use smart pointers. :)
GMan
+3  A: 

What if it's a const pointer?

Mark Ransom