2

It is often stated (e.g. here cppreference) that defining the left hand side (lhs) parameter of an arithmetic operator by value helps optimizing chained operations.

X operator+( X         lhs
           , X const & rhs )

To ensure that I don't accidently change lhs within the function, I like to declare my by value parameters const. Does this change the behavior concerning the desired optimization?

X operator+( X const   lhs
           , X const & rhs )
DrPepperJo
  • 632
  • 1
  • 5
  • 19

1 Answers1

3

Taking by copy is done to enable a specific idiom, when + is implemented in terms of +=:

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

On the other hand, if you take lhs by const X& reference, you would have to either make a copy yourself, like this

inline X operator+(const X& lhs, const X& rhs) {
    X res(lhs); 
    res += rhs;
    return res;
}

or to construct a new object, like this:

inline X operator+(const X& lhs, const X& rhs) {
    X res; 
    ... // Modify res to contain the sum of lhs and rhs
    return res;
}

If you are using the idiomatic approach, the compiler can optimize chains of + for you by making a copy once. The compiler notices that when you do this

lhs + rhs1 + rhs2

the result of lhs + rhs1 is a throw-away copy which can be reused in constructing (lhs + rhs1) + rhs2 without performing a copy again.

On the other hand, if you use one of the alternatives above, the compiler would need to make a copy for each operation in the chain.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks for addressing the chaining question so adequatly. In "Effective C++", Scott Meyers votes in favor of having the binary arithmetic operator functions return a const value to have the compiler detect errors like `if( a + b = c)`. Would this const affect the optimization in any way? – DrPepperJo Dec 07 '16 at 17:58
  • @DrPepperJo I don't think that it would, because the compiler "owns" the temporary object that it optimizes out, so it knows that there's no real assignment going on (assuming there's no bugs in the optimizer). – Sergey Kalinichenko Dec 07 '16 at 18:14