上节 C++11 右值引用(2)提到移动构造和移动赋值,本节介绍 std::move 函数。
一 作用
std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object.
In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.
std::move将左值转换成右值引用。头文件<utility>。看个例子:
#include <iostream>
#include <type_traits>
int a = 1;
cout << "a is_lvalue_reference: " << is_lvalue_reference<decltype(a)>::value << endl;
cout << "a is_rvalue_reference: " << is_rvalue_reference<decltype(a)>::value << endl;
cout << "move(a) is_lvalue_reference: " << is_lvalue_reference<decltype(move(a))>::value << endl;
cout << "move(a) is_rvalue_reference: " << is_rvalue_reference<decltype(move(a))>::value << endl;
结果如下:
二 使用
当了解了移动构造和移动赋值函数后,第一感觉是鸡肋,因为你不知道怎么传参数,而std::move则提供了移动语义。
看一段代码吧:
#include <iostream>
// MyString 在C++11 右值引用(2)中定义
MyString func()
{
cout << "call func " << endl;
MyString str("world", 6);
return std::move(str);
}
cout << "output1---------------------------" << endl;
MyString str("hello", 6);
MyString str1 = std::move(str); // 移动构造
MyString str2(std::move(str)); // 移动构造
cout << "output2---------------------------" << endl;
MyString str3;
str3 = std::move(str); // 移动赋值
cout << "output3---------------------------" << endl;
str = func();
cout << "end---------------------------" << endl;
结果如下:
三 参考