Re: Checking whether a pointer has been deleted
Edson Manoel wrote:
How does one test whether a pointer has been deleted or not.
You can always zero your pointers after a delete, e.g:
MyClass* p = new myClass();
delete p;
p = 0;
if (p) // ...
That doesn't help much unless you can be 100% sure of finding
all of the pointers to the object.
An even better solution, when possible, is to arrange for the
pointer to go out of scope immediately after the delete.
one always had to check with pointers but with references
there is never a need to. Or am I missing something here?
It depends. You can have invalid references too, e.g:
MyClass* p = new myClass();
delete p;
CallByRef(*p);
//...
void CallByRef(MyClass &p) {
p->something; // invalid access
}
Here, the error is present in the call itself, not in the called
function. But that doesn't really change your point; invalid
references are definitly possible.
You can use smart pointers too, see
http://www.boost.org/libs/smart_ptr/smart_ptr.htm, they are
better checked and better behaved after a 'deletion'.
The boost pointers normally take care of the deletion
themselves. The standard auto_ptr is probably more like what
you are looking for: assign NULL to it, and the object will be
deleted. It also ensures that there is only that one pointer to
the object, so you don't have to worry about other pointers
dangling.
Of course, it also ensures that there is only that one pointer
to the object, so if you need other pointers to the object, you
need a different solution.
--
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! ]