peter koch
12/15/2008 5:51:00 PM
On 15 Dec., 18:40, S S <sarvesh.si...@gmail.com> wrote:
> Hi
>
> I have some weird question, "It is always said to assign NULL after
> delete", i.e.,
> delete obj; obj = NULL; // to prevent multiple deletions crash, we
> assign NULL to obj
This is false in the general case: Often (almost always), there is no
need to set the pointer to 0.
>
> We don't do like this,
> if (obj != NULL) { delete obj; obj = NULL;} since NULL check is
> already inserted by compiler.
>
> Why don't compiler assign NULL for us? Is keeping deleted pointer is
> of any use? I didn't see any.
>
No - the value of the pointer is not valid anymore, but there are
several reasons that you don't/can't set a pointer to null after
deletion.
*) performance: there could be situations, where the extra code/time
used by this function should be avoided. These cases are rare, but do
exist in constrained environments.
*) validity: Often the zeroing wont help:
void f(int* p) { ... delete p; }
setting p to 0 above will not give you anything.
*) feasability: the stuff to delete might not be a left-hand value. In
these cases, you can't set the pointer to 0 anyway.
Last, it is very easy to write a helper-function that does this for
you:
template< typename T >
void delete_and_clear(T* &p) { delete p; p = 0; }
/Peter