Modern C++ std::move的实现原理

前言

有一节我们分析了std::bind的实现原理,本节稍作休息分析一个比较简单的std::move

原理

std::move的原理太简单了,一句话:就是把传进来的参数强转为右值引用类型。作用为调用移动构造函数,或移动赋值函数。下面通过例子和代码说明。

例子

#include <iostream>
#include <cstring>

using namespace std;

struct Thing {
    Thing()
    {
        cout << "default construct\n";
    }

    // Copy operator
    Thing(const Thing& other)
    {
        cout << "copy constructor\n";
    }

    // Move constructor
    Thing(Thing&& other) noexcept
    {
        cout << "move constructor\n";
    }

    // assignment operator
    Thing& operator=(const Thing& rhs) {
        cout << "copy operator\n";
        return *this;
    }

    // move assignment operator
    Thing& operator=(Thing&& rhs) noexcept {
        cout << "move operator\n";
        return *this;
    }

    // destructor necessary since we are working in dangerous new/delete territory
    ~Thing() noexcept {
        cout << "destructor " << "\n";
    }
};
int main()
{
    cout << "main::constructing a\n";
    Thing a;

    cout << "main::moving a to newly constructed c\n";
    Thing c(std::move(a));

    Thing x = std::move(c);
    
	cout << ">main::thing y\n";
	Thing y;
	y = std::move(x);

    return 0;
}

[mzhai@c++11]$ ./a.out
main::constructing a
default construct
main::moving a to newly constructed c
move constructor //Thing c(std::move(a));
move constructor //Thing x = std::move©;
main::thing y
default construct
move operator //y = std::move(x);
destructor
destructor
destructor
destructor

a, c, x虽然都是左值,但std::move却把它们强转成了右值引用,从而调用了move语义的函数而不是copy语义的。

std::move源码

 92   /**
 93    *  @brief  Convert a value to an rvalue.
 94    *  @param  __t  A thing of arbitrary type.
 95    *  @return The parameter cast to an rvalue-reference to allow moving it.
 96   */
 97   template<typename _Tp>
 98     constexpr typename std::remove_reference<_Tp>::type&&
 99     move(_Tp&& __t) noexcept
100     { return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }

让我们看看remove_reference 的定义,看看它是怎么脱去类型的外衣的:

1402   /// remove_reference
1403   template<typename _Tp>
1404     struct remove_reference
1405     { typedef _Tp   type; };
1406
1407   template<typename _Tp>
1408     struct remove_reference<_Tp&>
1409     { typedef _Tp   type; };
1410
1411   template<typename _Tp>
1412     struct remove_reference<_Tp&&>
1413     { typedef _Tp   type; };

原来不管你原来的类型是左值引用还是右值引用,统统都定义type为脱去外衣的类型。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深山老宅

鸡蛋不错的话,要不要激励下母鸡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值