为什么C ++在默认情况下不移动构造右值引用? [英] Why doesn't C++ move construct rvalue references by default?

查看:154
本文介绍了为什么C ++在默认情况下不移动构造右值引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下功能

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

为什么需要使用std::move()param强制转换回右值?因为param的类型是右值,因为它已在函数签名中声明为右值引用,所以不是很明显吗?是否不应该仅根据此原则在此处自动调用move构造函数?

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?

推荐答案

:

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

    Widget store_last = param; // boom    
}

采用当前设计:

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.

这篇关于为什么C ++在默认情况下不移动构造右值引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆