barney barney - 1 month ago 6
C++ Question

Why doesn't C++ move construct rvalue references by default?

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?

Answer Source

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 it's 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.