C++11 右值引用(3)std::move

上节 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;

结果如下:

三 参考

cppreference.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值