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.
[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.
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.
Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With