在单行中通过 XOR 交换整数。在 C++11 中真的允许吗?

Swap integers via XOR in single line. Is it really allowed in c++11?

我还是没看明白x ^= y ^= x ^= y; 在 C++11 中有效(正如他们在 thread 中所说)还是会导致未定义的行为?

link 给出的理由看起来很有说服力,但是 clang 抛出一个 warning:

warning: unsequenced modification and access to 'x' [-Wunsequenced]

此外,如果两个版本:

x ^= y ^= x ^= y; // (1) 
x = x ^ (y = y ^ (x = (x ^ y))); // (2)

被认为是等效的(并且在 C++11 中定义明确),为什么它给出不同的结果 (first, second)?

此外,需要注意的是,gcc 仅在第二版代码中给出了 warning 关于序列点的信息。

The assignment operator (=) and the compound assignment operators all group right-to-left. [..]
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.

因此您的代码等同于

x = x ^ (y ^= (x ^= y)));

... x 在 x = x ... 中仅计算一次。 不幸的是,对于 xor,操作数的评估是无序的。 IE。

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

适用。但是现在我们遇到了一个问题:

   x = x ^ (y ^= (x ^= y)));
//     *          ******
//     |            |
//     |            Side effect
//     Value computation

价值计算(隐含在对最左边的两个 xx 的单数求值中)和副作用彼此无序,因此我们得出 UB:

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.