【C++11】 右值引用和移动语义

目录

一、C++11的发展历史

二、列表初始化

2.1 C++98传统的{}

2.2 C++11中的{}

2.3 C++11中的std::initializer_list

三、右值引用和移动语义

3.1 左值和右值

3.2 左值引用和右值引用

3.3 引用延长生命周期

​编辑

3.4 左值和右值的参数匹配


一、C++11的发展历史

C++11 是 C++ 的第二个主要版本,并且是从 C++98 起的最重要更新。它引入了大量更改,标准化了既有实践,并改进了对 C++ 程序员可用的抽象。在它最终由 ISO 在 2011 年 8 月 12 日采纳前,人们曾使用名称“C++0x”,因为它曾被期待在 2010 年之前发布。C++03 与 C++11 期间花了 8 年时间,故而这是迄今为止最长的版本间隔。从那时起,C++ 有规律地每 3 年更新一次。

二、列表初始化

2.1 C++98传统的{}

struct Point
{
	int _x;
	int _y;
};
int main()
{
	int array1[] = { 1, 2, 3, 4, 5 };
	int array2[5] = { 0 };
	Point p = { 1, 2 };
	return 0;
}

2.2 C++11中的{}

  • C++11以后想统一初始化方式,试图实现一切对象皆可用{}初始化,{}初始化也叫做列表初始化。
  • 内置类型支持,自定义类型也支持,自定义类型本质是类型转换,中间会产生临时对象,最后优化了以后变成直接构造。
  • {}初始化的过程中,可以省略掉=
  • C++11列表初始化的本意是想实现一个大统一的初始化方式,其次他在有些场景下带来的不少便
  • 利,如容器push/inset多参数构造的对象时,{}初始化会很方便
#include<iostream>
#include<vector>
using namespace std;
struct Point
{
	int _x;
	int _y;
};
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
		:_year(year)
		, _month(month)
		, _day(day)
	{
		cout << "Date(int year, int month, int day)" << endl;
	}
	Date(const Date& d)
		:_year(d._year)
		, _month(d._month)
		, _day(d._day)
	{
		cout << "Date(const Date& d)" << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
// 一切皆可用列表初始化,且可以不加=

int main()
{
	// C++98支持的
	int a1[] = { 1, 2, 3, 4, 5 };
	int a2[5] = { 0 };
	Point p = { 1, 2 };
	// C++11支持的
	// 内置类型支持
	int x1 = { 2 };
	// 自定义类型支持
	// 这里本质是用{ 2025, 1, 1}构造一个Date临时对象
	// 临时对象再去拷贝构造d1,编译器优化后合二为一变成{ 2025, 1, 1}直接构造初始化d1
	// 运行一下,我们可以验证上面的理论,发现是没调用拷贝构造的
	Date d1 = { 2025, 1, 1 };
	// 这里d2引用的是{ 2024, 7, 25 }构造的临时对象
	const Date& d2 = { 2024, 7, 25 };
	// 需要注意的是C++98支持单参数时类型转换,也可以不用{}
	Date d3 = { 2025 };
	Date d4 = 2025;

	// 可以省略掉=
	Point p1{ 1, 2 };
	int x2{ 2 };
	Date d6{ 2024, 7, 25 };
	const Date& d7{ 2024, 7, 25 };

	// 不支持,只有{}初始化,才能省略=
	// Date d8 2025;
	vector<Date> v;
	v.push_back(d1);
	v.push_back(Date(2025, 1, 1));
	// 比起有名对象和匿名对象传参,这里{}更有性价比
	v.push_back({ 2025, 1, 1 });
	return 0;
}

2.3 C++11中的std::initializer_list

上面的初始化已经很方便,但是对象容器初始化还是不太方便,比如一个vector对象,我想用N个
值去构造初始化,那么我们得实现很多个构造函数才能支持, vector<int> v1 ={1,2,3};vector<int> v2 = {1,2,3,4,5};

C++11库中提出了一个std::initializer_list的类, auto il = { 10, 20, 30 }; // thetype of il is an initializer_list ,这个类的本质是底层开一个数组,将数据拷贝过来,std::initializer_list内部有两个指针分别指向数组的开始和结束。

initializer_list,std::initializer_list支持迭代器遍历。

容器支持一个std::initializer_list的构造函数,也就支持任意多个值构成的{x1,x2,x3...} 进行初始化。STL中的容器支持任意多个值构成的{x1,x2,x3...} 进行初始化,就是通过std::initializer_list的构造函数支持的。

// STL中的容器都增加了一个initializer_list的构造
vector(initializer_list<value_type> il, const allocator_type& alloc =
	allocator_type());
list(initializer_list<value_type> il, const allocator_type& alloc =
	allocator_type());
map(initializer_list<value_type> il, const key_compare& comp =
	key_compare(), const allocator_type& alloc = allocator_type());
// ...

template<class T>
class vector {
public:
	typedef T* iterator;
	vector(initializer_list<T> l)
	{
		for (auto e : l)
			push_back(e)
	}
private:
	iterator _start = nullptr;
	iterator _finish = nullptr;
	iterator _endofstorage = nullptr;
};
// 另外,容器的赋值也支持initializer_list的版本
vector& operator= (initializer_list<value_type> il);
map& operator= (initializer_list<value_type> il);
#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	std::initializer_list<int> mylist;
	mylist = { 10, 20, 30 };
	cout << sizeof(mylist) << endl;

	// 这里begin和end返回的值initializer_list对象中存的两个指针
	// 这两个指针的值跟i的地址跟接近,说明数组存在栈上
	int i = 0;
	cout << mylist.begin() << endl;
	cout << mylist.end() << endl;
	cout << &i << endl;

	// {}列表中可以有任意多个值
	// 这两个写法语义上还是有差别的,第一个v1是直接构造,
	// 第二个v2是构造临时对象+临时对象拷贝v2+优化为直接构造
	vector<int> v1({ 1,2,3,4,5 });
	vector<int> v2 = { 1,2,3,4,5 };
	const vector<int>& v3 = { 1,2,3,4,5 };

	// 这里是pair对象的{}初始化和map的initializer_list构造结合到一起用了
	map<string, string> dict = { {"sort", "排序"}, {"string", "字符串"} };

	// initializer_list版本的赋值支持
	v1 = { 10,20,30,40,50 };

	return 0;
}

三、右值引用和移动语义

C++98的C++语法中就有引用的语法,而C++11中新增了的右值引用语法特性,C++11之后我们之前学习的引用就叫做左值引用。无论左值引用还是右值引用,都是给对象取别名。

3.1 左值和右值

左值是一个表示数据的表达式(如变量名或解引用的指针),一般是有持久状态,存储在内存中,我们可以获取它的地址,左值可以出现赋值符号的左边,也可以出现在赋值符号右边。定义时const修饰符后的左值,不能给他赋值,但是可以取它的地址

右值也是一个表示数据的表达式,要么是字面值常量、要么是表达式求值过程中创建的临时对象
等,右值可以出现在赋值符号的右边,但是不能出现出现在赋值符号的左边,右值不能取地址

值得一提的是,左值的英文简写为lvalue,右值的英文简写为rvalue。传统认为它们分别是leftvalue、right value 的缩写。现代C++中,lvalue 被解释为loactor value的缩写,可意为存储在内存中、有明确存储地址可以取地址的对象,而 rvalue 被解释为 read value,指的是那些可以提供数据值,但是不可以寻址,例如:临时变量,字面量常量,存储于寄存器中的变量等,也就是说左值和右值的核心区别就是能否取地址。

#include<iostream>
using namespace std;
int main()
{
	// 左值:可以取地址
	// 以下的p、b、c、*p、s、s[0]就是常见的左值
	int* p = new int(0);
	int b = 1;
	const int c = b;
	*p = 10;
	string s("111111");
	s[0] = 'x';

	cout << &c << endl;
	cout << (void*)&s[0] << endl;

	// 右值:不能取地址
	double x = 1.1, y = 2.2;
	// 以下几个10、x + y、fmin(x, y)、string("11111")都是常见的右值
	10;
	x + y;
	fmin(x, y);
	string("11111");

	//cout << &10 << endl;
	//cout << &(x+y) << endl;
	//cout << &(fmin(x, y)) << endl;
	//cout << &string("11111") << endl;
	return 0;
}

3.2 左值引用和右值引用

Type& r1 = x; Type&& rr1 = y; 第一个语句就是左值引用,左值引用就是给左值取别名,第二个就是右值引用,同样的道理,右值引用就是给右值取别名。

左值引用不能直接引用右值,但是const左值引用可以引用右值

右值引用不能直接引用左值,但是右值引用可以引用move(左值)

template <class T> typename remove_reference<T>::type&& move (T&&arg);

move是库里面的一个函数模板,本质内部是进行强制类型转换,当然他还涉及一些引用折叠的知识

需要注意的是变量表达式都是左值属性,也就意味着一个右值被右值引用绑定后,右值引用变量变量表达式的属性是左值

语法层面看,左值引用和右值引用都是取别名,不开空间。从汇编底层的角度看下面代码中r1和rr1汇编层实现,底层都是用指针实现的,没什么区别。底层汇编等实现和上层语法表达的意义有时是背离的,所以不要然到一起去理解,互相佐证,这样反而是陷入迷途。

#include<iostream>
using namespace std;

template <class _Ty>
remove_reference_t<_Ty>&& move(_Ty&& _Arg)
{	// forward _Arg as movable
	return static_cast<remove_reference_t<_Ty>&&>(_Arg);
}

int main()
{
	// 左值:可以取地址
	// 以下的p、b、c、*p、s、s[0]就是常见的左值
	int* p = new int(0);
	int b = 1;
	const int c = b;
	*p = 10;
	string s("111111");
	s[0] = 'x';
	double x = 1.1, y = 2.2;

	// 左值引用给左值取别名
	int& r1 = b;
	int*& r2 = p;
	int& r3 = *p;
	string& r4 = s;
	char& r5 = s[0];

	// 右值引用给右值取别名
	int&& rr1 = 10;
	double&& rr2 = x + y;
	double&& rr3 = fmin(x, y);
	string&& rr4 = string("11111");

	// 左值引用不能直接引用右值,但是const左值引用可以引用右值
	const int& rx1 = 10;
	const double& rx2 = x + y;
	const double& rx3 = fmin(x, y);
	const string& rx4 = string("11111");

	// 右值引用不能直接引用左值,但是右值引用可以引用move(左值)
	int&& rrx1 = move(b);
	int*&& rrx2 = move(p);
	int&& rrx3 = move(*p);
	string&& rrx4 = move(s);
	string&& rrx5 = (string&&)s;

	// b、r1、rr1都是变量表达式,都是左值
	cout << &b << endl;
	cout << &r1 << endl;
	cout << &rr1 << endl;

	// 这里要注意的是,rr1的属性是左值,所以不能再被右值引用绑定,除非move一下
	int& r6 = r1;
	// int&& rrx6 = rr1;
	int&& rrx6 = move(rr1);

	return 0;
}

3.3 引用延长生命周期

右值引用可用于为临时对象延长生命周期,const 的左值引用也能延长临时对象生存期,但这些对象无法被修改。

#include<iostream>
using namespace std;

int main()
{
	std::string s1 = "Test";
	// std::string&& r1 = s1;			// 错误:不能绑定到左值

	const std::string& r2 = s1 + s1;	// OK:到 const 的左值引用延长生存期
	// r2 += "Test";					// 错误:不能通过到 const 的引用修改

	std::string&& r3 = s1 + s1;			// OK:右值引用延长生存期
	r3 += "Test";						//OK:能通过到非 const 的引用修改

	std::cout << r3 << '\n';

	return 0;
}

3.4 左值和右值的参数匹配

C++98中,我们实现一个const左值引用作为参数的函数,那么实参传递左值和右值都可以匹配。

C++11以后,分别重载左值引用、const左值引用、右值引用作为形参的f函数,那么实参是左值会匹配f(左值引用),实参是const左值会匹配f(const 左值引用),实参是右值会匹配f(右值引用)。

#include<iostream>
using namespace std;
void f(int& x)
{
	std::cout << "左值引用重载 f(" << x << ")\n";
}
void f(const int& x)
{
	std::cout << "到 const 的左值引用重载 f(" << x << ")\n";
}
void f(int&& x)
{
	std::cout << "右值引用重载 f(" << x << ")\n";
}
int main()
{
	int i = 1;
	const int ci = 2;

	f(i); // 调用 f(int&)
	f(ci); // 调用 f(const int&)
	f(3); // 调用 f(int&&),如果没有 f(int&&) 重载则会调用 f(const int&)
	f(std::move(i)); // 调用 f(int&&)

	// 右值引用变量在用于表达式时是左值
	int&& x = 1;
	f(x); // 调用 f(int& x)
	f(std::move(x)); // 调用 f(int&& x)
	return 0;
}


总结:

  • 左值引用和右值引用的最终目的:减少拷贝,提高效率
  • 左值引用还可以修改参数,方便使用

左值引用的不足:
     部分场景只能船只返回,不能左值引用返回(当前函数局部对象,出了当前函数作用域生命周期就销毁了,不能用左值引用返回,只能传值返回


本篇文章先简单介绍一下左值和右值,下篇具体讲一下右值引用的使用场景!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值