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

徘徊边缘 提交于 2019-11-26 22:25:31

问题


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.



来源:https://stackoverflow.com/questions/45843974/why-doesnt-c-move-construct-rvalue-references-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!