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);
...
};
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+), , . ? , - .