我正在阅读著名的 Undefined Behavior can cause time travel发布并注意到这部分:
First of all, you might notice the off-by-one error in the loop control. The result is that the function reads one past the end of the table array before giving up. A classical compiler wouldn't particularly care. It would just generate the code to read the out-of-bounds array element (despite the fact that doing so is a violation of the language rules), and it would return true if the memory one past the end of the array happened to match.
A post-classical compiler, on the other hand, might perform the following analysis:
The first four times through the loop, the function might return true.
When i is 4, the code performs undefined behavior. Since undefined behavior lets me do anything I want, I can totally ignore that case and proceed on the assumption that i is never 4. (If the assumption is violated, then something unpredictable happens, but that's okay, because undefined behavior grants me permission to be unpredictable.)
根据这篇文章,(较新的)编译器已经可以在编译时对未定义的行为采取行动,这意味着它在某些情况下完全能够发现未定义的行为。而不是通过消除 UB 代码或只是转换它来让恶魔飞出你的 Nose 或产生龙,因为它是允许的,为什么编译器不只是发出这可能不是故意的警告?
最佳答案
编译器的工作是将代码从高级语言编译到低级语言。如果您收到描述性错误或警告消息,是时候感谢编译器为您做了额外的工作。要获得所需的警告,请使用一些 static code analysis工具。
并且规范中没有明确定义的任何内容都是未定义的,并且不可能准备一份完整的未定义行为列表。可能无法对所有此类行为发出警告。
实际上,在许多情况下,编译器会警告未定义的行为,特别是在 gcc 上使用适当的警告标志,如 -W -Wall -Wextra -O2
。 (使用像 -O2
这样的优化标志,编译器会对代码进行回归分析,并可能产生更多警告)
关于c++ - 如果可能存在未定义行为,为什么编译器不警告您?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942101/