A rule is not strictly necessary because a language can exist without it; it is just a decision made by the standards committee. A null pointer is not a valid memory address. However, I would like to believe that every decision is made for some reason, and these reasons deserve attention.
This rule simplifies the management of cases of failure and other instances in which the pointer may be null. This is a simple, inexpensive check, and it adds notable convenience to the language.
For example, if there are many conditions that will lead to the allocation of dynamic memory, but there are others that will not, the convenience will simply insert 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, every call to delete would be surrounded ...
if(ptr)
... and that would be lame. Since this will be the norm, essentially a binding convention, why not just eliminate the need to fully verify? Why require an additional 5 characters (minimum) for each delete call?
Ed S.
source share