I'm surprised that this works:

double x = 3;
double y = 2;

(x *= 2) += y;
std::cout << x << std::endl;

The result is 8, which is what it looks like the programmer is trying to achieve. But I thought assignment operators returned an rvalue - how is it that you can assign to the result of one?

有帮助吗?

解决方案

The assignment operators for the built in types return an lvalue in C++ (unlike in C). But you cannot use it to modify the object without an intervening sequence point, so your example is undefined behavior (in C++03—C++11 changed a lot here, and I seem to remember that one of the results made your code defined).

Regardless of the situation with regards to undefined behavior, you would be better off writing:

x = 2 * x + y;

It's far more readable. The fact that the assignment operators result in lvalues is really only usable when the results are bound immediately to a reference:

T&
SomeClass::f()
{
    //  ...
    return aTinSomeClass += 42;
}

And even then, I'd write it in two statements.

(The general rule in C++ is that if the result of an operator corresponds to the value of an object in memory, then it is an lvalue. There was no general rule in C.)

其他提示

In C++ the result of the assignment operators, including the compound assignment operators (such as *=) are l-values, and thus assignables.

In C they are r-values, so your code invalid C code.

In C++, compound assignment operators return lvalues, as per §5.17/1:

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

In this case, the use of *= returns an lvalue denoting the object x which is then used as the left operand of the += operator.

Perhaps you are thinking of the simple arithmetic operators like + and * which do return rvalues.

In C, these operators don't return lvalues and therefore the result can't be further assigned.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top