一旦遇到归类为未定义行为的构造,是否允许 C++ 编译器发出随机代码? [英] Is a C++ compiler allowed to emit random code once it encounters a construct that is classified as undefined behavior?
问题描述
可能的重复:
未定义、未指定和实现定义的行为
我试图加深对 C++ 中未定义行为的理解.假设 C++ 编译器会有意检测一些未定义行为的情况 - 例如,在两次之间修改变量两次序列点:
I'm trying to deepen my understanding of undefined behavior in C++. Suppose a C++ compiler will intentionally detect some cases of undefined behavior - for example, modifying the variable twice between two sequence points:
x++ = 2;
一旦虚拟编译器可靠地检测到这种情况,它就会说向生成的机器代码中发出十个完全随机的机器指令.
Once that imaginary compiler reliably detects such a situation it will say emit ten totally random machine instructions into the produced machine code.
根据 C++ 标准,任何被归类为 UB 的地方都没有对会发生什么.所描述的虚构编译器是否符合 C++ 标准?
According to C++ standard, wherever something is classified as UB there're no requirements on what happens. Will the described imaginary compiler be conformant to the C++ standard?
推荐答案
是的.该标准没有要求,因此它可以为所欲为:
Yes. The standard imposes no requirements, so it can do whatever it wants:
未定义的行为
行为,例如可能出现在使用错误的程序构造或错误的数据,为此国际标准规定没有要求.
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 上,它将拒绝编译:
Just as a note, that is undefined behavior, but it's not necessarily a good example. On g++ 4.4.1, it will refuse to compile with:
错误:左操作数需要左值任务
error: lvalue required as left operand of assignment
因为后增量的结果不是左值.
because the result of a post-increment is not an lvalue.
这篇关于一旦遇到归类为未定义行为的构造,是否允许 C++ 编译器发出随机代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!