【C++】左值与右值

2024-06-06 18:48
文章标签 c++ 右值 左值

本文主要是介绍【C++】左值与右值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 左值与右值

到了代码的下一行,是否能通过单一变量访问到值。若访问不到,就是右值;否则就是左值。字面量一定是右值

#include <iostream>
using namespace std;#define func(x) __func(x, "func(" #x ")")void __func(int &x, const char *str) {cout << str << " is left value" << endl;return ;
}void __func(int &&x, const char *str) {cout << str << " is right value" << endl;return ;
}//之所以+重载不返回引用,而+=重载返回引用
//就是因为两个操作的结果值的类型不同
class A {
public ://因为+表达式的结果是右值A operator+(int x) {}// += 表达式的结果是左值A &operator+=(int x) {}
};int main() {func(1234);int x = 1234, y = 456;//到了下一行依然能通过x访问到x的值func(x);//x+y的结果是个临时匿名变量,所以到下一行的时候无法访问到该结果值,所以x+y返回值的类型是右值func(x + y);//x++值是x+1之前的值,到下一行无法通过x访问到x+1之前的值func(x++);//x+1以后的值,可以通过x访问到该值,所以++x的值是左值func(++x);//到了代码下一行无法通过单一变量访问到x+123的结果func(x + 123); //右值//到了代码下一行可以通过x访问到 x *= 2的结果func(x *= 2); //左func(y += 3); //左func(y * 3); //右return 0;
}

运行结果:
image-20210313160322553

2. 左值引用和右值引用

右值引用是绑定到右值上的引用,右值引用的定义形式是 int &&;左值引用的定义形式是int &

正确传递左值和右值的关系:

#include <iostream>
using namespace std;#define func(x) __func(x, "func(" #x ")")
#define func2(x) __func2(x, "func2(" #x ")")void __func2(int &x, const char *str) {cout << str << " is left value" << endl;return ;
}void __func2(int &&x, const char *str) {cout << str << " is right value" << endl;return ;
}void __func(int &x, const char *str) {cout << str << " is left value" << endl;func2(x);return ;
}
//int &&x是右值引用
void __func(int &&x, const char *str) {cout << str << " is right value" << endl;//func2(x); //x表现出的是左值特性//func2(move(x));//强制变成右值特性func2(forward<int &&>(x));//以右值引用的形式向下传递,x会保持右值引用的特性,可以理解为强制转换,但是比强制转换更强大,可以转换为某种类型的引用return ;
}//之所以+重载不返回引用,而+=重载返回引用
//就是因为两个操作的结果值的类型不同
class A {
public ://因为+表达式的结果是右值A operator+(int x) {}// += 表达式的结果是左值A &operator+=(int x) {}
};int main() {func(1234);int x = 1234, y = 456;//到了下一行依然能通过x访问到x的值func(x);//x+y的结果是个临时匿名变量,所以到下一行的时候无法访问到该结果值,所以x+y返回值的类型是右值func(x + y);//x++值是x+1之前的值,到下一行无法通过x访问到x+1之前的值func(x++);//x+1以后的值,可以通过x访问到该值,所以++x的值是左值func(++x);//到了代码下一行无法通过单一变量访问到x+123的结果func(x + 123); //右值//到了代码下一行可以通过x访问到 x *= 2的结果func(x *= 2); //左func(y += 3); //左func(y * 3); //右return 0;
}

运行结果:
image-20210313191612706
moveforward 函数为什么重要呢?本质原因是C++有重载,保证用正确的类型向下传递,保证可以调用到正确的函数重载形式。

forward 叫做 完美转发,比强制转换更厉害的是可以转换为某种类型的引用。

3. 引用绑定的顺序

#include <iostream>
using namespace std;void func1(int &x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}void func1(const int &x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}void func1(int &&x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}void func1(const int &&x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}int main() {int n;const int y = 123;func1(n); //func1(int &);func1(y); //func1(const int &)func1(123 + 456); //func1(int &&)return 0;
}

运行结果:
image-20210313200227802
const 类型的左值引用可以绑定所有数据类型:

#include <iostream>
using namespace std;/*void func1(int &x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}*/void func1(const int &x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}/*void func1(int &&x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}void func1(const int &&x) {cout << __PRETTY_FUNCTION__ << "called" << endl;
}*/int main() {int n;const int y = 123;func1(n); //func1(int &);func1(y); //func1(const int &)func1(123 + 456); //func1(int &&)return 0;
}

运行结果:
在这里插入图片描述
不能绑定到func(int &)是因为在func1(int &)中是可能修改该值的,常量值是不能绑定到int &的,但是func1(const int &)是不能修改的参数的,所以绑定到func1(const int &)是为了包含所有情况。绑定顺序就是优先绑定和自己类型匹配的引用,否则绑定到const类型的左值引用。

4. 移动构造

/*************************************************************************> File Name: move_ctor.cpp> Author: Maureen > Mail: Maureen@qq.com > Created Time: 二  1/11 16:17:49 2022************************************************************************/#include <iostream>
using namespace std;
//实现自己的vector
namespace maureen {
class vector {
public :vector(int n = 10) : __size(n), data(new int[n]) {cout << "default constructor" << endl;}vector(const vector &v) : __size(v.size()), data(new int[__size]) {cout << "deep copy constructor" << endl;for (int i = 0; i < size(); i++) ++data[i] = v[i];return ;}//合并两个动态数组vector operator+(const vector &v) {vector ret(v.size() + this->size());vector &now = *this;for (int i = 0; i < size(); i++) {ret[i] = now[i];}for (int i = size(); i< ret.size(); i++) {ret[i] = v[i - size()];}return ret;}int &operator[](int ind) const {return this->data[ind];}int size() const { return __size; }
private :int __size;int *data;
};
}//end of maureenostream &operator<<(ostream &out, const maureen::vector &v) {for (int i = 0; i < v.size(); i++) {out << v[i] << " ";}return out;
}int main() {maureen::vector v1, v2;for (int i = 0; i < v1.size(); i++) v1[i] = rand() % 100;for (int i = 0; i < v2.size(); i++) v2[i] = rand() % 100;maureen::vector v3(v1 + v2);cout << v1 << endl;cout << v2 << endl;cout << v3 << endl;return 0;
}

有返回值优化的运行结果:
image-20210313192938872
没有返回值优化的运行结果:
image-20210313194434931
maureen::vector v3(v1 + v2); 中的 v1+v2 会产生一个临时变量,但是却对这个临时变量做了拷贝,这没有必要,何不直接将临时变量的值拿过来。

所以就产生了一类特殊的构造函数: 移动构造

拷贝构造传入的是左值引用,所以在拷贝构造中,必须得做深拷贝;构造函数可以传左值引用,也可以传右值引用。

一旦调用了右值引用对象,说明传入的值是临时值,要不然不会绑定到右值引用上。这种情况下,就直接抢。这就是移动构造:

vector(vector &&v) : __size(v.size()), data(v.data) {v.data = nullptr; //因为有时候可能是在显式调用移动构造v.__size = 0;
}

移动构造就是传入右值引用的构造。

#include <iostream>
using namespace std;
//实现自己的vector
namespace maureen {
class vector {
public :vector(int n = 10) : __size(n), data(new int[n]) {cout << "default constructor" << endl;}vector(const vector &v) : __size(v.size()), data(new int[__size]) { //拷贝构造cout << "deep copy constructor" << endl;for (int i = 0; i < size(); i++) ++data[i] = v[i];return ;}vector(vector &&v) : __size(v.size()), data(v.data) { //移动构造cout << "move copy constructor" << endl;v.data = nullptr;v.__size = 0;}vector operator+(const vector &v) { //合并两个动态数组vector ret(v.size() + this->size());vector &now = *this;for (int i = 0; i < size(); i++) {ret[i] = now[i];}for (int i = size(); i< ret.size(); i++) {ret[i] = v[i - size()];}return ret;}int &operator[](int ind) const {return this->data[ind];}int size() const { return __size; }~vector() {if (data) delete[] data;data = nullptr;__size = 0;}
private :int __size;int *data;
};
}//end of maureenostream &operator<<(ostream &out, const maureen::vector &v) {for (int i = 0; i < v.size(); i++) {out << v[i] << " ";}return out;
}int main() {maureen::vector v1, v2;for (int i = 0; i < v1.size(); i++) v1[i] = rand() % 100;for (int i = 0; i < v2.size(); i++) v2[i] = rand() % 100;maureen::vector v3(v1 + v2);cout << v1 << endl;cout << v2 << endl;cout << v3 << endl;return 0;
}

去掉返回值优化后的结果:
image-20210313194740273
移动构造只是改变了指针的指向,而拷贝构造需要先创建一片存储区再将数据拷贝过来。

发现当前值是临时值的时候,就将它的资源抢过来。

C++因为引入左值引用和右值引用,重回巅峰。因为在有移动构造之前,STL效率不高,因为只要产生拷贝就是深拷贝,如 string,vector。

当拷贝构造是深拷贝时,就一定要配一个移动构造。

显式调用移动构造函数:

#include <iostream>
using namespace std;
//实现自己的vector
namespace maureen {
class vector {
public :vector(int n = 10) : __size(n), data(new int[n]) {cout << "default constructor" << endl;}vector(const vector &v) : __size(v.size()), data(new int[__size]) {cout << "deep copy constructor" << endl;for (int i = 0; i < size(); i++) ++data[i] = v[i];return ;}vector(vector &&v) : __size(v.size()), data(v.data) {cout << "move copy constructor" << endl;v.data = nullptr;v.__size = 0;}vector operator+(const vector &v) { //合并两个动态数组vector ret(v.size() + this->size());vector &now = *this;for (int i = 0; i < size(); i++) {ret[i] = now[i];}for (int i = size(); i< ret.size(); i++) {ret[i] = v[i - size()];}return ret;}int &operator[](int ind) const {return this->data[ind];}int size() const { return __size; }~vector() {if (data) delete[] data;data = nullptr;__size = 0;}
private :int __size;int *data;
};
}//end of maureenostream &operator<<(ostream &out, const maureen::vector &v) {for (int i = 0; i < v.size(); i++) {out << v[i] << " ";}return out;
}
int main() {maureen::vector v1, v2;for (int i = 0; i < v1.size(); i++) v1[i] = rand() % 100;for (int i = 0; i < v2.size(); i++) v2[i] = rand() % 100;maureen::vector v3(v1 + v2);cout << v1 << endl;cout << v2 << endl;cout << v3 << endl;maureen::vector v4(move(v1));//显式调用移动构造cout << v1 << endl;cout << v4 << endl;return 0;
}

去掉返回值优化的运行结果:
image-20210313194908978

这篇关于【C++】左值与右值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

从入门到精通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