【问题标题】:why std::move takes forward_reference instead of lvaue reference [duplicate]为什么 std::move 采用 forward_reference 而不是 lvaue 引用 [重复]
【发布时间】:2017-07-04 09:02:08
【问题描述】:

只是为了确认我对std::move的理解

std::move - 将 T& 转换为 T&& 以便 T's 移动构造函数将启动(如果存在,否则复制 ctor 将发挥其作用,除非我们没有从外部删除移动 ctor/赋值) .

当我查看std::move 的可能实现时,就像

template<typename T>
typename remove_reference<T>::type&& move(T&& param)
{
using ReturnType =typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}

它使用 remove_reference&lt;T&gt; 的原因是因为引用折叠应用于 forward_reference T&amp;&amp;

我只是想知道为什么我们需要前向引用,我们不能这样做吗

template<typename T>
T&& moveInQuestion(T& p){
  return static_cast<T&&>(p);
}

struct someType{};
someType lvalref;
static_assert(is_same<decltype(moveInQuestion(lvalref)),decltype(std::move(lvalref))>::value,"");

static_assert 没有失败。

而且我还认为std::move 的价值类别是lvalue,在这种情况下moveInQuestion 可能比std::move 更好吗?

【问题讨论】:

    标签: c++ c++11 move-semantics


    【解决方案1】:

    通常的例子是通用代码

    template<class T>
    T frob() {
        std::vector<T> x = /* ... */;
        return std::move(x[0]);
    }
    

    使用您的move,当Tbool 时,这会中断,因为在这种情况下x[0] 是prvalue 代理引用而不是左值。

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2013-07-10
      • 2019-07-09
      • 1970-01-01
      相关资源
      最近更新 更多