I remember reading somewhere that it's neccessary for delete NULL
to be a valid operation in C++, but I can't remeber the reason why it should be so. Would someone please remind me?
Exact Reason:
Possible Reasoning:
delete
in user code.The rule is not strictly necessary in that the language could exist without it; it is simply a decision made by the standards committee. The null pointer is not a valid memory address. However, I would like to believe that each decision is made for a reason, and those reasons are worth knowing.
This rule simplifies the management of failure cases and other instances in which a pointer may be null. It is an easy, inexpensive check to make, and it adds appreciable convenience to the language.
For example, if many conditions exist which would result in dynamic memory allocation, but others also exist which will not, it's convenient to be able to just stick a delete
at the end and not worry about it.
// contrived example
void foo(int n) {
char *p = nullptr;
switch(n) {
case whatever:
case something_else:
p = new char[n];
break;
}
// some code...
delete [] p; // look Ma, no check!
}
If delete nullptr
were illegal then every call to delete
would be surrounded by...
if(ptr)
...and that would be lame. Since this would be the norm, an essentially mandatory convention, why not just eliminate the need to check entirely? Why require an extra 5 characters (minimum) for every call to delete
?
First off, NULL
is never a valid pointer value (in a hosted C++ program), and so there's no ambiguity as to whether the pointer points to a live object or not. Second, the internal memory management logic must do its own checking anyway to do the bookkeeping, so presumably nothing would be gained from mandating that the pointer be non-null.
So now we know that there's nothing speaking against this rule, here's the big argument in its favour: It makes it much easier to write code. Consider this simple exception-handling piece of allocation code:
T * p1 = NULL;
T * p2 = NULL;
T * p3 = NULL;
try
{
p1 = new T;
p2 = new T;
p3 = new T;
}
catch (...)
{
delete p1;
delete p2;
delete p3;
throw;
}
This is simple and uncluttered. If we needed to add NULL-checks everywhere, it would make the code a lot less readable and obscure the code's logic.
Because the Standard committee know that no program can have NULL to point to a valid object, i.e NULL cannot point to a valid memory so it is safe to write delete NULL
, precisly because it doesn't actually delete anything. Since that is safe, then it saves you from the need to check for NULL , before delete
:
//if (ptr != NULL) NOT NEEDED
delete ptr; //safe even if ptr == 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