我们都听过这样的警告:如果您在 C 或 C++ 中调用未定义的行为,任何事情都可能发生。
这是否仅限于任何运行时行为,还是还包括任何编译时行为?特别是,编译器在遇到调用未定义行为的构造时是否允许拒绝代码(在标准中没有其他要求的情况下),甚至崩溃?
最佳答案
"You're all ignoring the actual definition and focusing on the note, The standard imposes no requirements." - @R.MartinhoFernandes
上面的消息是由给定用户在 Lounge<C++> 中编写的 并提出了一个非常有效的论点;当涉及调用未定义行为的代码时,该标准不会强加任何要求。
<小时/>! ! !
未定义行为甚至延伸到编译器解析输入数据(即代码)的最远角落,正如以下来自C++11<的引用所验证的那样/em> 和 C99 标准。
用一句话回答你的问题;
- 未定义的行为不仅限于运行时执行,并且允许在编译期间崩溃“以环境特征的记录方式” 1
“以环境特征的记录方式”是一种奇怪的陈述,您几乎可以编写一个编译器来记录它可能会在任何给定代码上崩溃(这是无效的)以赋予它崩溃的可能性。
1.引用C++11/C99标准
<小时/>### c++11
###1.3.24 [defns.undefined]
Undefined behavior; behavior for which this International Standard imposes no requirements
[ Note:
Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data.
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
block 引用>Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.
<小时/>— end note ]
### c99
3.4.3 - Undefined Behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this >International Standard imposes no requirements
NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
关于c++ - "undefined behaviour"是否扩展到编译时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627496/