Re: delete a pointer
On May 9, 1:38 pm, =D6=F6 Tiib <oot...@hot.ee> wrote:
On 8 mai, 21:23, James Kanze <james.ka...@gmail.com> wrote:
On May 7, 4:40 pm, =D6=F6 Tiib <oot...@hot.ee> wrote:
On May 7, 5:34 pm, Jorgen Grahn <grahn+n...@snipabacken.se> wrote:
On Fri, 2010-05-07, gwowen wrote:
On May 7, 2:12 pm, Back9 <backgoo...@gmail.com> wrote:
It's good practice -- it does almost no harm and can turn
Heisenbugs into predictable crashes.
It will also hide bugs from memory debuggers (which are in
wide use these days, with valgrind being available for
free). I don't like the rule at all -- I find it harmful (as
a general rule).
What bugs will hide:
delete a;
a = NULL;
From what it will hide these? Sounds surprizing. It exposes
bugs and does not hide. You should explain how this rule is
harmful.
It creates the impression that it exposes bugs, but it
doesn't. (I don't think it hides any, however. It just
gives a false sense of security.)
It does give that "this pointer does not propagate dangling
values" sense of security. How this is false sense?
Because that's not normally a problem. (Unless you only have
one pointer in your application.)
The one case such a rule might make sense is if you're using
garbage collection, since a garbage collector won't collect
the memory if there is a valid pointer to it (even if the
destructor has run). Most of the time, even there, however,
there's no point in it, since the pointer will either be
reused, or go out of scope.
Assigning 0 to pointer is valid form of reusing it. 0 is
useful value of pointer. Value that points at unavailable
places causes bugs when it is used.
Assigning null to a pointer is a valid form of reusing it. No
problem with that. So is assigning some other value to it,
e.g.:
delete p;
p = new Something;
In this case, assigning null to p between the two statements
might even be useful, if the new fails.
But how often do you reuse pointers?
The only time this rule makes any sense at all is if the
pointer will be reused, but not immediately, and you have to
check to determine whether it is already in use before
reusing it. (The classical example is a cached computed
value. If you do anything which might change the value, you
delete and null the pointer, and if you need the value, you
check for null before recalculating it.)
It seems like there are just fixed set of cases. In some cases
assigning 0 is pointless and in other cases it is fruitful.
The cases when the rule does not make sense are when pointer
is immediately reused again or leaves scope or is destroyed
itself.
The problem is that most people who propose the rule aren't
thinking in terms of reuse. They're arguing safety.
--
James Kanze