Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X().Y(Z()) and the order of evaluation in standard

Can somebody quote the corresponding paragraph of the C++ standard that says that the order of the std::string construction and foo() call is unspecified in the following case:

std::string().append(foo());

I know that there's 5.2.2.8 but it states about function arguments, not several function calls between the same sequence points:

The order of evaluation of function arguments is unspecified

like image 945
FrozenHeart Avatar asked Dec 05 '22 17:12

FrozenHeart


2 Answers

It was widely believed that leaving the order of expression evaluation undefined led to more optimizations. It was probably true 10 and 20 years ago, but it does not appear to be so any more. Data to that effect was presented to the committee, but I don't know if it is published anywhere.

like image 86
Bjarne Stroustrup Avatar answered Dec 08 '22 07:12

Bjarne Stroustrup


5/4 [expr]:

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified

Because operators are functions, this means string() will be constructued either before or after foo().

Also see: Order of function call

"Bjarne Stroustrup also says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2, with some reasoning:

Better code can be generated in the absence of restrictions on expression evaluation order.

Also see: Order of evaluation in C++ function parameters

like image 37
Jossie Calderon Avatar answered Dec 08 '22 09:12

Jossie Calderon