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

S

S S

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
 
P

peter koch

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
 
A

Andrey Tarasevich

S said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top