c++ - "undefined behaviour"是否扩展到编译时?

标签 c++ c runtime undefined-behavior compile-time

我们都听过这样的警告:如果您在 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标准

<小时/>

###

###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).

Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.

end note ]

<小时/>

###

3.4.3 - Undefined Behavior

  1. behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this >International Standard imposes no requirements

  2. 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/

相关文章:

C++ 如何扫描用户输入的字符串中的特定单词?

c - pthread_t 指针作为 pthread_create 的参数

objective-c - 具有上下文的确定性随机数生成器?

字符数组转整数

ios - 如何调整 NSURLSession 方法 dataTaskWithUrl

c++ - 指向成员函数怪异的指针

c++ - C++中类定义的问题

c++将存储在链表中的两个大数相乘

collections - 通过System.Collections.Queue传递对象时丢失类型信息

iPhone:如何获取一个类的所有属性?