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?
I remember reading somewhere that it’s neccessary for delete NULL to be a valid
Share
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
deleteat the end and not worry about it.If
delete nullptrwere illegal then every call todeletewould be surrounded by……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?