gpt4 book ai didi

c++ - 复合赋值 E1 op= E2 不等同于 E1 = E1 op E2

转载 作者:太空狗 更新时间:2023-10-29 23:48:32 24 4
gpt4 key购买 nike

cppreference说:

the behavior of every builtin compound-assignment expression E1 op= E2 (where E1 is a modifiable lvalue expression and E2 is an rvalue expression or a braced-init-list (since C++11)) is exactly the same as the behavior of the expression E1 = E1 op E2, except that the expression E1 is evaluated only once and that it behaves as a single operation with respect to indeterminately-sequenced function calls (e.g. in f(a += b, g()), the += is either not started at all or is completed as seen from inside g())."

我想知道这个解释是错误的(不充分的)还是我理解有误。

我知道 E1 = E1 + E2E1 += E2 之间存在内在差异,这是解释 here :

#include<iostream>
int main() {

int x;

x = 1;
x += (-1) ? 2 : 2;
std::cout << x << std::endl; //prints 3

x = 1;
x = x + (-1) ? 2 : 2;
std::cout << x << std::endl; //prints 2

x = 2;
x += (-2) == 0;
std::cout << x << std::endl; //prints 2

x = 2;
x = x + (-2) == 0; // prints 1

}

我的猜测是 E1 op= E2 具有以下行为:

  • E1E2进行求值(顺序不确定),将两次求值之间的运算结果赋值给E1,即 (E1) = (E1) 运算 (E2)

那么对复合赋值操作行为的更好解释是(E1) = (E1) 操作 (E2)? (或者E1 = E1 op (E2),因为E1只能有优先级高于赋值运算符和优先级低于op运算符的运算符,没有括号,如果 E1 op (E2) 想要产生与 (E1) op (E2) 不同的结果。这种结果是可修改左值的运算符不存在。)

最佳答案

cppreference 的引用直接来自 C++ 标准:

[expr.ass]/6

The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.
Such expressions are deprecated if E1 has volatile-qualified type; see [depr.volatile.type].
For += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type.
In all other cases, E1 shall have arithmetic type.

在这种情况下,the term expression has already been definedE1 op= E2 等价于 E1 = E1 op E2 显然并不意味着表达式在它们的文本表示上是等价的,但在它们的解析(类型、值和副作用)。

[A] better explanation for compound assignment operation's behavior could be (E1) = (E1) op (E2)?

我只能表达我的意见:我认为 cpprederence 页面在这里引用标准是正确的,但可以添加注释以确保读者不会误解。

关于c++ - 复合赋值 E1 op= E2 不等同于 E1 = E1 op E2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com