How many temporary objects are created when two objects are combined without optimizing the return value?

I decided to ask this question by reading articles 20 and 22 of Scott Meyers' book, More Effective C ++.

Say you wrote a class to represent rational numbers:

class Rational
{
public:
    Rational(int numerator = 0, int denominator = 1);

    int numerator() const;
    int denominator() const;

    Rational& operator+=(const Rational& rhs); // Does not create any temporary objects
    ...
};

Now let's say that you decide to implement operator+with operator+=:

const Rational operator+(const Rational& lhs, const Rational& rhs)
{
    return Rational(lhs) += rhs;
}

My question is: if return value optimization was disabled, how many temporary variables would be created operator+?

Rational result, a, b;
...
result = a + b;

I believe that 2 temporary ones are created: one, when Rational(lhs)executed inside the body operator+, and the other, when the value returned operator+is created by copying the first temporary.

My confusion arose when Scott introduced this operation:

Rational result, a, b, c, d;
...
result = a + b + c + d;

: ", 3 , operator+". , , 6 ( 2 operator+), , . ? , - .

+6
4

, , .

result = a + b + c + d; , 3 , 1- a + b, - temporary#1 + c, - temporary#2 + d, result. . .

, , , .

+3

, , , - , a + b * c * d

:

a + (b + (c + d))

, . .

+1

. , , ( "" ).

as-if. optimizing.

. CppCon 2017 Matt Godbolt" ? .

+1

a+b+c+d , ( RVO ). .

operator + , Rational(lhs)+=a, prvalue Rational(lhs) operator+=, [over.match.func]/5.1 (. [expr.call]/4)

const-, rvalue , .

, , [class.temporary]/2.1

[...]:

  • prvalue

, operator +.

Rational(lhs)+=a, - , Rational(Rational(lhs)+=a) prvalue (a prvalue , - phi: ), operator +. [class.temporary]/2.1 2 :

  • a+b,
  • (a+b)+c

, 4 . operator+ 5-

operator + - . [class.temporary]/2.6: ​​

[...]:

  • prvalue .

6- .

RVO , pr. GCC -fno-elide-constructors .

operator +:

const Rational operator+(Rational lhs, const Rational& rhs)
{
    return lhs += rhs;
}

With this definition prvalue a+band (a+b)+cbe directly used for initialization of the first parameter operator +, which saves you from materialization two time series. See assembly here .

+1
source

All Articles