问题
C++03 Standard say's:
5.3.5 Delete
[...] In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.[...]
char *p = nullptr;
delete p; //no effect
It means, it is valid to delete null pointer in c++.
What C++17 standard say about calling delete on nullptr pointer?
回答1:
Yes it is valid, and it results in a noop. reference
If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.
回答2:
For destructors, [expr.delete]/6:
If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.
This technically doesn't say that if the operand is a null pointer value, the destructor isn't invoked. Probably a minor wording issue?
For deallocation, [expr.delete]/7:
If the value of the operand of the delete-expression is a null pointer value, it is unspecified whether a deallocation function will be called as described above.
Unspecified deallocation, but likely no destruction.
Note also, from [basic.stc.dynamic.deallocation]/3, which clarifies that even if the standard library deallocation function is called in this situation, there is no effect:
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
来源:https://stackoverflow.com/questions/47354881/what-c17-standard-say-about-calling-delete-on-nullptr