I often see legacy code checking for NULL
before deleting a pointer, similar to,
if (NULL != pSomeObject) { delete pSomeObject; pSomeObject = NULL; }
Is there any reason to checking for a NULL
pointer before deleting it? What is the reason for setting the pointer to NULL
afterwards?
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.
In c++03 it is pretty clear that deleting a null pointer has no effect. Indeed, it is explicitly stated in §5.3. 5/2 that: In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.
You should not write code that performs deletion of null pointer. If you use delete on uninitialized pointer, void pointer, then behaviour of program is undefined. Better practice is to stop using new & delete . This is C++ not Java & C#.
Commonly, the null pointer is used to denote the end of a memory search or processing event. In computer programming, a null pointer is a pointer that does not point to any object or function. A nil pointer is a false value. For example, 1 > 2 is a nil statement.
It's perfectly "safe" to delete a null pointer; it effectively amounts to a no-op.
The reason you might want to check for null before you delete is that trying to delete a null pointer could indicate a bug in your program.
Edit
NOTE: if you overload the delete operator, it may no longer be "safe" to delete 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