Why doesn't C++ move construct rvalue referenc

2019-01-26 05:49发布

问题:

This question already has an answer here:

  • Rvalue Reference is Treated as an Lvalue? 4 answers
  • Lvalue reference constructor is called instead of rvalue reference constructor 1 answer

Say I have the following function

void doWork(Widget && param)  // param is an LVALUE of RRef type
{
    Widget store = std::move(param); 
}

Why do I need to cast param back to an rvalue with std::move()? Shouldn't it be obvious that the type of param is rvalue since it was declared in the function signature as an rvalue reference? Shouldn't the move constructor be automatically invoked here on this principle alone?

Why doesn't this happen by default?

回答1:

with your design:

void doWork(Widget && param)
{
    Widget store1 = param;     // automatically move param
    Widget store2 = param;     // boom

    Widget store_last = param; // boom    
}

with current design:

void doWork(Widget && param)
{
    Widget store1 = param;                // ok, copy
    Widget store2 = param;                // ok, copy

    Widget store_last = std::move(param); // ok, param is moved at its last use
}

So the moral here is that even if you have an rvalue reference you have a name for it which means you can use it multiple times. As such you can't automatically move it because you could need it for a later use.