Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for NULL before delete in C++ - good practice? [duplicate]

Possible Duplicate:
Is there any reason to check for a NULL pointer before deleting?

I know that The C++ language guarantees that delete p will do nothing if p is equal to NULL. But constantly in different projects, articles, examples I see that it is checking for NULL before delete. Usually in format

    if(pObj)
       delete pObj;

Why is it so? Some historical reasons? I'm totally confused about how to do delete objects right.

like image 794
HelloHi Avatar asked Dec 11 '12 10:12

HelloHi


People also ask

Do I need to check for NULL before delete p?

[16.8] Do I need to check for NULL before delete p? No! The C++ language guarantees that delete p will do nothing if p is equal to NULL.

Should I set pointer to NULL after delete?

Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors. There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt.

Is it OK to delete nullptr?

Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

Do you have to delete a null pointer?

Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either. If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.


3 Answers

Why is it so?

Ignorance. Some people do not know that delete(NULL); is not doing anything.

You can not really check if the pointer is really valid. If you delete twice, you are invoking an undefined behavior.

like image 188
BЈовић Avatar answered Sep 23 '22 22:09

BЈовић


No this is completely pointless. delete will not delete a pointer that is already set to null! So delete a null pointer all your like!

like image 33
goji Avatar answered Sep 23 '22 22:09

goji


delete is an operator and it invokes a destructor. When the delete operator is used with NULL nothing happens, so same as all the answers already it is pointless to check for null.

like image 23
Konstantin Dinev Avatar answered Sep 21 '22 22:09

Konstantin Dinev