Why doesn't GCC optimize out deletion of null pointers in C++?

后端 未结 6 1174
情歌与酒
情歌与酒 2021-02-02 05:54

Consider a simple program:

int main() {
  int* ptr = nullptr;
  delete ptr;
}

With GCC (7.2), there is a call instruction regardi

6条回答
  •  感情败类
    2021-02-02 06:45

    According to C++14 [expr.delete]/7:

    If the value of the operand of the delete-expression is not a null pointer value, then:

    • [ ...omitted... ]

    Otherwise, it is unspecified whether the deallocation function will be called.

    So both compilers do comply with the standard, because it's unspecified whether operator delete is called for deletion of a null pointer.

    Note that the godbolt online compiler just compiles the source file without linking. So the compiler at that stage must allow for the possibility that operator delete will be replaced by another source file.

    As already speculated in another answer -- gcc may be angling for consistent behaviour in the case of a replacement operator delete; this implementation would mean that someone can overload that function for debug purposes and break on all invocations of the delete expression, even when it happened to be deleting a null pointer.

    UPDATED: Removed speculation that this might not be a practical issue, since OP provided benchmarks showing that it in fact is.

提交回复
热议问题