C + C++ = 未定义的行为?
当代码
U = C + C++;
以不同的方式运行 时,我遇到了问题标准类型和我自己的类型。 我有一个示例 http://ideone.com/4S1uA 其中 int 和我的类 Int 有不同的值,它应该代表真正的 Int 工作方式。
是否有可能使我的类的行为与标准 int 的工作方式相同?这段代码有未定义的行为吗?
为什么它是不可定义的行为? C++ 有一个操作优先级,所以应该首先评估 c++
,因为它改变了 a 的值,所以对于加法作为第一个参数应该是传递了 a
的新值,并传递了旧值作为第二个值。对于 Int 类是这样的,但对于标准 int 则不然。
Possible Duplicate:
How do we explain the result of the expression (++x)+(++x)+(++x)?
Undefined Behavior and Sequence Points
I have the problem, when the code
U = C + C++;
Runs in different way for standart types and for my own types.
I have an example http://ideone.com/4S1uA where I have different values for int and my class Int, which should represent the way real Int works.
Is it possible to make my class behave the same way, as the standard int works? Has this code undefined behavior?
WHY it is undefiend behaivior? C++ has an operation priorities, so the c++
should be evaluated first, as it change the value of a, so for addition as first argument should be passed new value of a
and as the second the old value. And it's works this way for class Int, but not for standart int.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。相对于副作用,操作数的求值顺序是未定义的。
该标准第 6.5(2) 节规定:
由于 int 是标量类型,并且这里的副作用是无序的,因此行为是未定义的。
你应该这样写你的代码:
Yes. The order in which the operands are evaluated, with respect to the side effect, is undefined.
Section 6.5(2) of the standard says:
Since
int
is a scalar type, and since the side effect here is unsequenced, the behavior is undefined.You should write your code like this:
是的,这是未定义的行为。您不能在同时修改变量的语句中访问该变量两次,因为未定义表达式“C”和表达式“C++”的求值顺序。
Yes, that is undefined behavior. You can't access a variable twice in a statement that also modifies it because the order in which the expression 'C' and the expression 'C++' are evaluated is not defined.
这里涉及到的概念是序列点之一。引用维基百科文章的开头句:
在 C 语言中,
+
运算符不会创建序列点。因此,副作用的顺序没有定义。然而,在 C++ 中,重载运算符 + 是函数调用,它确实会创建序列点。这会在副作用方面产生不同的行为。请注意,虽然未指定函数参数求值的顺序,但所有副作用都会在函数进入之前完成。因此,如果C + C++
涉及重载的+
运算符,则C++
副作用将应用于+ 的左侧参数
在+
函数执行之前。这与 int 值的情况不同,在 int 值的情况下,在右侧的副作用完成之前可能会或可能不会评估左侧。The concept involved here is one of sequence points. To quote the opening sentence from the Wikipedia article:
In C, the
+
operator does not create a sequence point. Therefore the order of side effects is not defined. However, in C++, an overloadedoperator +
is a function call, which does create a sequence point. This creates different behavior with respect to side effects. Note that while the order in which function arguments are evaluated is not specified, all side effects are completed before the function enters. So ifC + C++
involves an overloaded+
operator, then theC++
side effect will have been applied to the left argument of+
before the+
function executes. This is unlike the case forint
values, where the left side may or may not be evaluated before the side effect of the right side is complete.