C ++ Is a special rvalue variant of an overloaded operator required?

For questions + answers, such as Operator Overloading , it is pointed out that the best way to overload a binary operator, such as operator+:

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;
}
Herself

operator+takes lhsby value, rhsby reference, const and returns the changed value lhsby value.

I am having trouble understanding what will happen here if it is called with rvalue as lhs: whether it will still be the only definition that is needed (and the compiler optimizes the movement of the argument and the return value), or it makes sense to add a second overloaded version of the statement, which works with rvalue links?

EDIT:

, Boost.Operators :

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

Named Return Value, , :

, NRVO, , .

, , .

+4
2

:

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

r-, lvalues ​​ . lvalues ​​ lhs, x lhs, prvalues ​​ lhs.

lhs lhs const& , +. :

+====================+==============+=================+
|                    | X const& lhs | X lhs           |
+--------------------+--------------+-----------------+
| X sum = a+b;       | 1 copy       | 1 copy, 1 move  |
| X sum = X{}+b;     | 1 copy       | 1 move          |
| X sum = a+b+c;     | 2 copies     | 1 copy, 2 moves |
| X sum = X{}+b+c;   | 2 copies     | 2 moves         |
| X sum = a+b+c+d;   | 3 copies     | 1 copy, 3 moves |
| X sum = X{}+b+c+d; | 3 copies     | 3 moves         |
+====================+==============+=================+                

const&, . - . . - , , lvalue, ( xvalues).

- , - const&, , , .

, , , :

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

X operator+(X&& lhs, X const& rhs) {
    lhs += rhs;
    return std::move(lhs);
}

, . , .

+4

rvalue , . std:: move lhs. , rvalue.

0

Source: https://habr.com/ru/post/1668799/


All Articles