In questions+answers like Operator Overloading, it is stated that the best way to overload a binary operator such as operator+
is:
class X {
X& operator+=(const X& rhs)
{
// actual addition of rhs to *this
return *this;
}
};
inline X operator+(X lhs, const X& rhs)
{
lhs += rhs;
return lhs;
}
operator+
itself thus takes lhs
by value, rhs
by const reference and returns the altered lhs
by value.
I am having trouble understanding what would happen here if it would be called with an rvalue as lhs
: Would this still be the single definition that is needed (and will the compiler optimize the movement of the argument and the return value), or does it make sense to add a second overloaded version of the operator that works with rvalue references?
EDIT:
Interestingly, in Boost.Operators, they talk about this implementation:
T operator+( const T& lhs, const T& rhs )
{
T nrv( lhs );
nrv += rhs;
return nrv;
}
which allows Named Return Value Optimization but it is not used by default because:
Sadly, not all compiler implement the NRVO, some even implement it in an incorrect way which makes it useless here
This new information is not enough for me to provide a full answer, but it might allow some other bright minds to derive at an encompassing conclusion.