[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

why c++ compiler don't assign NULL for us

S S

12/15/2008 5:41:00 PM

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

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.

Thanks
3 Answers

peter koch

12/15/2008 5:51:00 PM

0

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

Obnoxious User

12/15/2008 8:01:00 PM

0

On Mon, 15 Dec 2008 09:40:31 -0800, S S 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
>

If you randomly delete the same pointer throughout
your code, then a design overhaul might be a good idea.

--
OU

Andrey Tarasevich

12/15/2008 11:44:00 PM

0

S S wrote:
> I have some weird question, "It is always said to assign NULL after
> delete",

"Always said"? Said where???

> i.e.,
> delete obj; obj = NULL; // to prevent multiple deletions crash, we
> assign NULL to obj

It doesn't prevent the multiple deletion problem in general.

> Why don't compiler assign NULL for us? Is keeping deleted pointer is
> of any use? I didn't see any.

Then don't keep it. But assigning NULL? It doesn't really solve anything.

--
Best regards,
Andrey Tarasevich