c++ - std :move 的魔力是什么

标签 c++ c++11 rvalue-reference

以下代码使 VC2010 失败:

//code1
std::string& test1(std::string&& x){
  return x;
}
std::string str("xxx");
test1(str);  //#1 You cannot bind an lvalue to an rvalue reference

//code2 
std::string&& test1(std::string&& x){
  return x;  //#2 You cannot bind an lvalue to an rvalue reference
}

有一些文章解释#1,但我不明白为什么#2 也失败。

让我们看看 std::move 是如何实现的

template<class _Ty> inline
    typename tr1::_Remove_reference<_Ty>::_Type&&
        move(_Ty&& _Arg)
    {   // forward _Arg as movable
    return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg);
    }
  1. move 的参数仍然是一个右值引用,但是 move(str) 是可以的!
  2. 移动也返回右值。

std:move 的魔力是什么?

谢谢

最佳答案

std::move的参数看起来像是一个右值引用,这看起来确实令人困惑 - 为什么你可以调用 move(str) , 当 str不是右值?

这里的技巧是右值引用在模板参数上的工作令人困惑:

如果模板参数Tint , 然后 T&&将是一个右值引用 int&& .
但是如果 T是左值引用 int& , 然后 T&&也将是左值引用 int& .

这是因为方式&&&合并:

Type & &&   ==  Type &
Type && &   ==  Type &
Type & &    ==  Type &
Type && &&  ==  Type &&

所以当你调用move(str) , Tstd::string& , 和 move<std::string&> 的参数类型也是std::string& - 一个左值引用,它允许函数调用编译。然后都是move所要做的就是将值转换为右值引用。

关于c++ - std :move 的魔力是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12193143/

相关文章:

c++ - 回想一下变量的先前值?

c++ - 如何在 C++ 中的一个应用程序中同时使用 TCP 和 UDP

c++ - 等待条件变量后线程未并行运行

c++ - 从其他容器中辨别 smart_pointer 的模板函数

C++ 在带有右值缓冲区的 ostream 中使用 snprintf,格式是否正确?

c++ - 通过 r 值引用接收后通过引用传递

c++ - 目标 `C++ 2008 Redistributable` 需要什么开发环境?

大约 10000 个类的 C++ 程序

c++ - std::declval 是如何工作的?

c++ - 什么时候 std::move 是多余的?