【cmu15445c++入门】(2)c++中的std::move() 左值引用右值引用

2024-01-09 17:12

本文主要是介绍【cmu15445c++入门】(2)c++中的std::move() 左值引用右值引用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

左值右值

要理解move语义,必须理解左值和右值的概念。左值的简化定义是左值是对象,指向内存中某个位置。右值是左值之外的任何。

std::move() 

move语义,在C++中是一个有用的方法,它允许在对象之间高效和优化地转移数据所有权。move语义的主要目标之一是提高性能,因为移动对象比深度复制对象更快、更高效。

std::move 是将对象从一个左值移动到另一个左值的最常见方法。

std::move 将表达式转换为右值。这允许我们将左值作为右值进行交互,并允许所有权从一个左值转移到另一个左值。

代码

/*** @file move_semantics.cpp* @author Abigale Kim (abigalek)* @brief Tutorial code for move semantics.*/// Move semantics in C++ are a useful concept that allows for the efficient
// and optimized transfer of ownership of data between objects. One of the
// main goals of move semantics is to increase performance, since moving an
// object is faster and more efficient than deep copying the object.
// move语义,在C++中是一个有用的方法,它允许在对象之间高效和优化地转移数据所有权。
// move语义的主要目标之一是提高性能,因为移动对象比深度复制对象更快、更高效// To understand move semantics, one must understand the concept of lvalues
// and rvalues. A simplified definition of lvalues is that lvalues are objects
// that refer to a location in memory. Rvalues are anything that is not a
// lvalue.
//要理解move语义,必须理解左值和右值的概念。左值的简化定义是左值是对象,指向内存中某个位置。右值是左值之外的任何。// std::move is the most common way of moving an object from one lvalue to
// another. std::move casts an expression to a rvalue. This allows for us to
// interact with a lvalue as a rvalue, and allows for the ownership to be
// transferred from one lvalue to another.
// std::move 是将对象从一个左值移动到另一个左值的最常见方法。
// std::move 将表达式转换为右值。这允许我们将左值作为右值进行交互,并允许所有权从一个左值转移到另一个左值。// In the code below, we include some examples for identifying whether
// expressions in C++ are lvalues or rvalues, how to use std::move, and passing
// rvalues references into functions.
//在下面的代码中,我们提供了一些示例,用于识别 C++ 中的表达式是左值还是右值,如何使用std::move以及将右值引用传递到函数中。// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes the utility header for std::move.
#include <utility>
// Includes the header for std::vector. We'll cover vectors more in
// containers.cpp, but what suffices to know for now is that vectors are
// essentially dynamic arrays, and the type std::vector<int> is an array of
// ints. Mainly, vectors take up a non-negligible amount of memory, and are here
// to show the performance benefits of using std::move.
#include <vector>// Function that takes in a rvalue reference as an argument.
// It seizes ownership of the vector passed in, appends 3 to
// the back of it, and prints the values in the vector.
// 这个函数传入一个右值引用,函数夺取传入的向量的所有权,并添加"3"在向量的最后,然后输出整个vector.
void move_add_three_and_print(std::vector<int> &&vec) {// 专利的move会产生"夺权"std::vector<int> vec1 = std::move(vec);vec1.push_back(3);for (const int &item : vec1) {std::cout << item << " ";}std::cout << "\n";
}// Function that takes in a rvalue reference as an argument.
// It appends 3 to the back of the vector passed in as an argument,
// and prints the values in the vector. Notably, it does not seize
// ownership of the vector. Therefore, the argument passed in would
// still be usable in the callee context.// 这个函数传入一个右值引用,函数中添加"3"在向量的最后,并打印向量中的值。
//值得注意的是,它不会夺取向量的所有权.因此,传入的参数在被调用方上下文中仍可用。
void add_three_and_print(std::vector<int> &&vec) {vec.push_back(3);for (const int &item : vec) {std::cout << item << " ";}std::cout << "\n";
}int main() {// Take this expression. Note that 'a' is a lvalue, since it's a variable that// refers to a specific space in memory (where 'a' is stored). 10 is a rvalue.int a = 10;//a是一个左值,因为它指向了一块特殊的内存空间。10是一个右值。// Let's see a basic example of moving data from one lvalue to another.// We define a vector of integers here.std::vector<int> int_array = {1, 2, 3, 4};// Now, we move the values of this array to another lvalue.std::vector<int> stealing_ints = std::move(int_array);// 一个左值move到另一个左值// Rvalue references are references that refer to the data itself, as opposed// to a lvalue. Calling std::move on a lvalue (such as stealing_ints) will// result in the expression being cast to a rvalue reference.// 右值引用是引用数据本身的引用,而不是左值。对左值(如 stealing_ints)调用std::move将导致表达式被强制转换为右值引用。std::vector<int> &&rvalue_stealing_ints = std::move(stealing_ints);// However, note that after this, it is still possible to access the data in// stealing_ints, since that is the lvalue that owns the data, not// rvalue_stealing_ints.//但是,请注意,在此之后,仍然可以在 stealing_ints 中访问数据,因为这是拥有数据的左值,而不是rvalue_stealing_ints。std::cout << "Printing from stealing_ints: " << stealing_ints[1] << std::endl;std::cout << "Printing from rvalue_stealing_ints: " << rvalue_stealing_ints[1] << std::endl;//这里下面这行直接报错退出,因为int_array对象的所有权已经没了。//std::cout << "Printing from int_array: " << int_array[1] << std::endl;// It is possible to pass in a rvalue reference into a function. However,// once the rvalue is moved from the lvalue in the caller context to a lvalue// in the callee context, it is effectively unusable to the caller.// Essentially, after move_add_three_and_print is called, we cannot use the// data in int_array2. It no longer belongs to the int_array2 lvalue.//可以将右值引用传递到函数中。但是,一旦右值从调用方上下文中的左值移动到被调用方上下文中的左值,//调用方实际上就无法使用它。从本质上讲,调用 move_add_three_and_print 后,//我们不能在 int_array2 中使用数据。它不再属于int_array2左值。std::vector<int> int_array2 = {1, 2, 3, 4};std::cout << "Calling move_add_three_and_print...\n";move_add_three_and_print(std::move(int_array2));// It would be unwise to try to do anything with int_array2 here. Uncomment// the code to try it out! (On my machine, this segfaults...) NOTE: THIS MIGHT// WORK FOR YOU. THIS DOES NOT MEAN THAT THIS IS WISE TO DO! // std::cout << int_array2[1] << std::endl;//如果在这里尝试使用int_array2,例如输出其中的一个值,那么会报错退出。因为在函数里面使用了move。// If we don't move the lvalue in the caller context to any lvalue in the// callee context, then effectively the function treats the rvalue reference// passed in as a reference, and the lvalue in this context still owns the// vector data.//如果在调用的函数里面没有使用move,那么函数会把右值引用转换为一个引用,情切左值仍然具有对象的使用权。std::vector<int> int_array3 = {1, 2, 3, 4};std::cout << "Calling add_three_and_print...\n";add_three_and_print(std::move(int_array3));// As seen here, we can print from this array.std::cout << "Printing from int_array3: " << int_array3[4] << std::endl;// 仅仅调用一次move方法std::vector<int> int_array4 = {1, 2, 3, 4};std::move(int_array4);std::cout << "Printing from int_array4: " << int_array4[1] << std::endl;// 调用move 给一个右值std::vector<int> int_array5 = {1, 2, 3, 4};std::vector<int> &&rvalue_stealing_intsstd5 = std::move(int_array5);std::cout << "Printing from rvalue_stealing_intsstd5: " << rvalue_stealing_intsstd5[1] << std::endl;std::cout << "Printing from int_array5: " << int_array5[1] << std::endl;// 调用move 给一个左值std::vector<int> int_array6 = {1, 2, 3, 4};std::vector<int> rvalue_stealing_intsstd6 = std::move(int_array6);std::cout << "Printing from rvalue_stealing_intsstd6: " << rvalue_stealing_intsstd6[1] << std::endl;// 下面这一行会报错退出std::cout << "Printing from int_array6: " << int_array6[1] << std::endl;return 0;
}

 

运行结果

这篇关于【cmu15445c++入门】(2)c++中的std::move() 左值引用右值引用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/587842

相关文章

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

C++11委托构造函数和继承构造函数的实现

《C++11委托构造函数和继承构造函数的实现》C++引入了委托构造函数和继承构造函数这两个重要的特性,本文主要介绍了C++11委托构造函数和继承构造函数的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、委托构造函数1.1 委托构造函数的定义与作用1.2 委托构造函数的语法1.3 委托构造函

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(