Re: Using NEW and DELETE operators?
On Oct 26, 12:13 am, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-10-26 00:03, Donos wrote:
I want to delete the pointer only if it's a valid pointer.
How to do that?
Why? Using delete on a null-pointer is a no-op, performing the check is
just a waste of code and execution time.
It's more a waste of programmer time; a good compiler could
optimize the check out, and even if it didn't, the difference in
execution time is not significant.
But his question stands. He didn't say he wanted to delete the
pointer only if it's non-null; he said he wanted to delete it
only if it's valid. And testing for null doesn't work, because
invalid pointers don't necessarily compare equal to null.
(Formally, even trying to compare an invalid pointer with null
results in undefined behavior. In practice, however, it will
usually just compare unequal---just like a valid pointer to an
object would.)
As for the answer to his question: you need some tool external
to C++, like Purify or valgrind, to do this. Such tools impose
a very significant runtime and space overhead, however, there
are probably licensing issues if you want to deliver the
software with the tool, and they generally don't convert the
operation to a no-op, but rather generate error messages, etc.
For pure memory management, of course, he can use the Boehm
collector, and forget the delete's entirely. This doesn't work
with objects which have a managed lifetime, of course, but
typically, if you're just conditionally deleting like he seems
to be, the object doesn't have a managed lifetime anyway.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34