为什么GCC不优化删除C

为什么GCC不优化删除C

本文介绍了为什么GCC不优化删除C ++中的空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

      31.3 [s]。

这些结果在许多运行中绝对一致且偏差最小。前两种情况之间的性能差异是显着的,我不会说这是一些像代码一样的非常罕见的角落案例。

解决方案

根据C ++ 14 [expr.delete] / 7:

这两个编译器都符合标准,因为它没有被指定是否调用 operator delete 来删除空指针。



请注意,godbolt在线编译器只是在不链接的情况下编译源文件。因此,该阶段的编译器必须允许将 operator delete 替换为另一个源文件。



正如在另一个答案中已经推测的那样 - 在替换 operator delete 的情况下,gcc可能会争取一致的行为。这个实现意味着某人可以为了调试目的而重载该函数,并且打破 delete 表达式的所有调用,即使它碰巧正在删除空指针。



更新:删除了这个可能不是实际问题的猜测,因为OP提供的基准证明它实际上是。


Consider a simple program:

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

With GCC (7.2), there is a call instruction regarding to operator delete in the resulting program. With Clang and Intel compilers, there are no such instructions, the null pointer deletion is completely optimized out (-O2 in all cases). You can test here: https://godbolt.org/g/JmdoJi.

I wonder whether such an optimization can be somehow turned on with GCC? (My broader motivation stems from a problem of custom swap vs std::swap for movable types, where deletion of null pointers can represent a performance penalty in the second case; see https://stackoverflow.com/a/45689282/580083 for details.)

31.3 [s].

These results were absolutely consistent across many runs with minimal deviation. The performance difference between first two cases is significant and I wouldn't say that this is some "exceedingly rare corner case" like code.

解决方案

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

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.

这篇关于为什么GCC不优化删除C ++中的空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:49