3

I am confused about explicit usage of the rvalue reference.

Suppose we have a class named ClassX and it has all copy and move methods. When I execute the code below, different copy methods have been invoked (copy constructor and move constructor). But I expect always move constructor is executed. Why copy constructor is invoked when i bind an object explicitly to an rvalue reference and use it as copy object?

ClassX c = std::move(object_c);  // Invokes move constructor

ClassX&& cr = std::move(object_c);
ClassX c = cr;  // Invokes copy constructor
Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
Suat Mutlu
  • 95
  • 3
  • 6
    If it has a name, it's an lvalue. `cr` is a name, it's an lvalue. – Eljay Jun 19 '23 at 11:09
  • 2
    An rvalue reference is bound to an rvalue. But whether this reference itself is or is not an rvalue is an entirely independent problem. – Daniel Langr Jun 19 '23 at 11:18
  • 4
    Correct, the code should do `ClassX c = std::move(cr);`. Keep in mind that `std::move` does **not** itself move anything, it only *allows* a move to occur as-if the variable were an unnamed temporary (such as a return value or result of an expression). It also allows a variable to be bound to an rvalue reference (usually something that is useful for parameter passing). If you find this to be confusing, you are not alone; it is confusing. – Eljay Jun 19 '23 at 11:18

0 Answers0