Re: Avoiding dangling pointers.
* Sean Hunt:
0 is an important value for pointers. It represents the null pointer -
an invalid value.
Sorry, but it's very valid. I suspect you meant that it's invalid with respect
to some high level assumptions for the program. But it's valid at the C++
language level.
Unfortunately the standard doesn't define what a valid pointer is.
But in a particular, a null-pointer value can be assigned without UB, it can be
compared without UB, and it can be dereferenced with well-defined result in a
typeof-expression, so we have a number of well-defined operations on this value.
Note that the standard talks about last-array-element-plus-one pointer as
valid even though it cannot be dynamically dereferenced: it's valid for
assignment and and equality checking. And a null pointer value supports that
and more.
There is a standard macro NULL that should be 0, and
you will frequently see that used. Pointers can be tested for validity
"if (ptr) { /* ... */ }", so if you assign 0 to a pointer that you
delete, you ensure that later code can check to make sure that the
code is valid.
What such an assignment does is not to make a valid pointer (variable) invalid,
but to make an invalid pointer valid.
That's probably not the intended effect, and anyways, generally ungood because
it can hide errors.
On the other hand, the dangling pointer just incurs UB, which is not guaranteed
to detect e.g. a second delete.
So what third hand is there?
Generally, to not call delete directly: let a smart pointer do that for you.
That smart pointer should be sufficiently smart to not call delete twice. :-)
Cheers, & hth.,
- Alf
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]