C++ Primer 笔记——理解std::move

标准库move函数是使用右值引用的模板的一个很好的例子。标准库是这样定义std::move的:函数

template <typename T>
typename remove_reference<T>::type&& move(T&& t)
{
    return static_cast<typename remove_reference<T>::type&&>(t);
}

 

咱们考虑以下代码的工做过程:rem

std::string s1("hi"), s2;
s2 = std::move(string("hi"));    // 正确,从一个右值移动数据
s2 = std::move(s1);                // 正确,可是在赋值以后,s1的值是不肯定的


在第一个赋值中,实参是string类型的右值,所以过程为:string

  • 推断T的类型为 string
  • remove_reference<string> 的 type 成员是 string
  • move 返回类型是 string&&
  • move 的函数参数t的类型为 string&&

所以,这个调用实例化 move<string>,即函数ast

string&& move(string &&t)


在第二个赋值中,实参是一个左值,所以:模板

  • 推断T的类型为 string&
  • remove_reference<string&> 的 type 成员是 string
  • move 返回类型是 string&&
  • move 的函数参数t的类型为 string& &&,会折叠成 string&

所以,这个调用实例化 move<string&>,即引用

string&& move(string &t)

 

  一般状况下,static_cast 只能用于其余合法的类型转换。可是有一条针对右值的特许规则:虽然不能隐式的将一个左值转换成右值引用,但咱们能够用static_cast显示的将一个左值转换为一个右值。数据

相关文章
相关标签/搜索