-
-
Notifications
You must be signed in to change notification settings - Fork 264
Assignment operator behavior #407
Description
TIL that:
expression1() = expression2();
is NOT(!) the same as:
expression1().operator=(expression2());
when expression1 and expression2 have side effects.
I am not truly an expert on this, but my current understanding is that:
expression1() = expression2();
has a defined order, see: http://eel.is/c++draft/expr.ass:
The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand; their result is an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand. With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation.
Important is that the right operand is sequenced before the left operand in case of using an assignment operator.
On the other hand, my current understanding (I may be wrong) is that if you have:
func1().func2(func3());
it is not specified in which order func1() and func3() should evaluate.
This wandbox link shows an example where:
expression1() = expression2()
is executed in a different order than
expression1().operator=(expression2());
It would be great if cppinsights could produce code showing in which order the evaluation occurs in the case of assignments
(because the sequencing is defined in that case). However, to make it more readable, splitting up the assignment into more statements should maybe only be done if there are actually function calls on both sides of the assignments.