首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

C++之std::move(移动语义)

  • 24-03-18 06:43
  • 2972
  • 6457
blog.csdn.net

相关系列文章

C++之std::is_object

C++之std::decay

C++模板函数重载规则细说

C++之std::declval

C++之std::move(移动语义)

C++之std::forward(完美转发)

C++之std::enable_if

C++之std::is_pod(平凡的数据)

目录

1.介绍

2.源码分析

3.优点

4.示例


1.介绍

在C++11中,标准库在中提供了一个有用的函数std::move,std::move并不能移动任何东西,它唯一的功能是将一个左值引用强制转化为右值引用,继而可以通过右值引用使用该值,以用于移动语义。

2.源码分析

以VS2019为例,std::move原型定义:

  1. template <class _Ty>
  2. _NODISCARD constexpr remove_reference_t<_Ty>&& move(_Ty&& _Arg) noexcept { // forward _Arg as movable
  3. return static_cast<remove_reference_t<_Ty>&&>(_Arg);
  4. }

remove_reference_t的定义如下:

  1. template <class _Ty>
  2. using remove_reference_t = typename remove_reference<_Ty>::type;

进一步推导remove_reference的定义如下:

  1. template <class _Ty>
  2. struct remove_reference { //原始的,最普通的版本
  3. using type = _Ty;
  4. using _Const_thru_ref_type = const _Ty;
  5. };
  6. template <class _Ty>
  7. struct remove_reference<_Ty&> { //左值引用
  8. using type = _Ty;
  9. using _Const_thru_ref_type = const _Ty&;
  10. };
  11. template <class _Ty>
  12. struct remove_reference<_Ty&&> { //右值引用
  13. using type = _Ty;
  14. using _Const_thru_ref_type = const _Ty&&;
  15. };

        首先,函数参数T&&是一个指向模板类型参数的右值引用,通过引用折叠,此参数可以与任何类型的实参匹配(可以传递左值或右值,这是std::move主要使用的两种场景)。关于引用折叠如下:

1)所有右值引用折叠到右值引用上仍然是一个右值引用。(A&& && 变成 A&&) 。
2)所有的其他引用类型之间的折叠都将变成左值引用。 (A& & 变成 A&; A& && 变成 A&; A&& & 变成 A&)。

简单来说,右值经过T&&传递类型保持不变还是右值,而左值经过T&&变为普通的左值引用。

3.优点

std::move将左值变为右值,再结合类的移动构造函数,实现所有权从一个对象转移到另一个对象,只是转移,没有内存的搬迁或者内存拷贝,从而极大地提高代码运行效率。

4.示例

  1. std::string old("12212412512");
  2. std::string new1 = std::move(old); //old变为""
  3. std::unique_ptr<int> pValue1(new int{ 5 });
  4. std::unique_ptr<int> pValue2 = std::move(pValue1); //pValue1清空
  5. std::vector<int> pInts = { 0, 1, 2, 3, 4, 5, 67, 1000 };
  6. std::vector<int> pInt1 = pInts; //pInt1拷贝pInts,和pInts一样
  7. std::vector<int> pInt2 = std::move(pInts); //pInts清空
注:本文转载自blog.csdn.net的流星雨爱编程的文章"https://blog.csdn.net/haokan123456789/article/details/134968560"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top