1

I am currently playing around with move semantics in C++. I tried to use r-value references in a custom constructor. Please see the following simplified example:

class MyClass
{
   public:
      // ....
      MyClass(MyClass&& pLeft, int pOp, MyClass&& pRight);
      MyClass(const MyClass& pLeft, int pOp, const MyClass& pRight);
      // ....
};

MyClass operator +(MyClass&& pLeft, MyClass&& pRight)
{
   return MyClass(pLeft, 1, pRight);
}

The operator+ is called as expected with pLeft and pRight being temporary objects. However then it calls the custom constructor using l-value references instead of the custom constructor using r-value references. Why?

There is a lot of information about r-value references and move semantics in the web. But it seems I skipped the detail that explains the mentioned behaviour.

Silicomancer
  • 8,604
  • 10
  • 63
  • 130
  • 2
    `pLeft` is not a temporary (because it has a name). You need to `std::move`. Yes, expression vs variable types are confusing. – Max Langhof Jun 11 '19 at 13:48
  • 2
    Remember, if something has a name, it is an lvalue. That is a important thing to remember when dealing with rvalue references and move semantics. – NathanOliver Jun 11 '19 at 13:50

0 Answers0