Re: Checking whether a pointer has been deleted
Antti Virtanen wrote:
On 2006-06-07, kanze <email@example.com> wrote:
probably after "delete p;" you have to write "p = 0;"
That doesn't really change anything. You can test if a pointer is
null, and in some cases, writing "p = NULL ;" makes sense, but it
only affects that one particular pointer, not other pointers to the
same element, and in the general case, is of no use whatsoever.
In my university, we recommend it to all students in programming
courses because accesses through the old pointer value might do
something, but accesses through null pointer are likely to trap right
at the moment of access.
And what about accesses through other pointers which happened to point
to the same object. As a general rule, it's bad, because it gives a
false sense of security. There are, of course, special cases, but they
are just that.
t* p = new t();
p->doSomething(); // UB, but might occasionally succeed
p = 0;
p->doSomething(); // will almost certainly abort the program right here
But how often is that a problem? Compared with something like:
T* p = new T() ;
SomeObject o( p ) ; // Stores p, and uses it in the
delete p ;
I'm not entirely sure if this zeroing is good style in the general
case, but the compiler can optimise it away in many cases. Personally
I don't like having to delete stuff manually anyway and prefer smart
pointers or automatic garbage collection.
Well, I'd say that garbage collection is the future. I use it in new
projects, when I can. (I've had problems using it with some third
libraries.) But even with manual management, I don't see where zeroing
the pointer buys you anything but a false sense of security, at least
the general case.
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]