c++ - 一旦遇到被归类为未定义行为的构造,是否允许 C++ 编译器发出随机代码?

标签 c++ undefined-behavior

<分区>

Possible Duplicate:
Undefined, unspecified and implementation-defined behavior

我正在努力加深对 C++ 中未定义行为的理解。假设 C++ 编译器将有意检测某些未定义行为的情况 - 例如,modifying the variable twice between two sequence points :

x++ = 2;

一旦想象中的编译器可靠地检测到这种情况,它就会说将十个完全随机的机器指令发送到生成的机器代码中

根据 C++ 标准,wherever something is classified as UB there're no requirements on what happens .所描述的假想编译器是否符合C++标准?

最佳答案

是的。该标准没有要求,因此它可以为所欲为:

undefined behavior

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.

请注意,这是未定义的行为,但这不一定是一个很好的例子。在 g++ 4.4.1 上,它将拒绝编译:

error: lvalue required as left operand of assignment

因为后增量的结果不是左值。

关于c++ - 一旦遇到被归类为未定义行为的构造,是否允许 C++ 编译器发出随机代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4265167/

相关文章:

c++ - 将 int*** 分配给 int[][][]

c++ - C 标准库可扩展性对 C++ 程序有多大影响?

c++ - int a =++i+++i 是未定义的行为吗?

c++ - 为什么一些标准运算符没有标准仿函数?

c++ - Gsoap Http 事件回调

c++ - 如何在 Windows 上使用命令行运行 UnitTest++

c++ - 这是不确定的吗?

C++ 对一个定义规则的混淆

c++ - 这段代码,为什么它必须显示未定义的行为?

c++ - 在 Linux 中测量 C++ 系统调用命令的时间