关于在 nullptr 上调用 delete,C++17 标准怎么说?
What C++17 standard say about calling delete on nullptr?
C++03 标准说法:
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
也就是说,在c++中删除空指针是有效的
C++17 标准对在 nullptr 指针上调用 delete 有何规定?
是的,它是有效的,它会导致 noop。 reference
If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.
对于析构函数,[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.
从技术上讲,这并不是说如果操作数 是 空指针值,则不会调用析构函数。可能是一个小的措辞问题?
对于重新分配,[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.
未指定的重新分配,但可能没有销毁。
另请注意,来自 [basic.stc.dynamic.deallocation]/3,它阐明了即使在这种情况下调用标准库释放函数,也没有任何效果:
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.
C++03 标准说法:
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
也就是说,在c++中删除空指针是有效的
C++17 标准对在 nullptr 指针上调用 delete 有何规定?
是的,它是有效的,它会导致 noop。 reference
If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.
对于析构函数,[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.
从技术上讲,这并不是说如果操作数 是 空指针值,则不会调用析构函数。可能是一个小的措辞问题?
对于重新分配,[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.
未指定的重新分配,但可能没有销毁。
另请注意,来自 [basic.stc.dynamic.deallocation]/3,它阐明了即使在这种情况下调用标准库释放函数,也没有任何效果:
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.