C++:C++11

前言:前面涉及C++11的知识点我们补充讲解过,现在这篇博客我们正式讲解C++11。

我尽量活成我想成为的模样,而不是某些人口中的‘他’。

我们每个人都在跟自己的业力对抗,都想努力变好,可是这个世界本身就是矛盾的。

愿吾之愿力能护持汝生生世世,不被世俗沉沦,看破诸法实相

C++11简介

2003 C++ 标准委员会曾经提交了一份技术勘误表 ( 简称 TC1) ,使得 C++03 这个名字已经取代了
C++98 称为 C++11 之前的最新 C++ 标准名称。不过由于 C++03(TC1) 主要是对 C++98 标准中的漏洞
进行修复,语言的核心部分则没有改动,因此人们习惯性的把两个标准合并称为 C++98/03 标准。
C++0x C++11 C++ 标准 10 年磨一剑,第二个真正意义上的标准珊珊来迟。 相比 C++98/03 C++11 则带来了数量可观的变化,其中包含了约 140 个新特性,以及对 C++03 标准中 600 个缺陷的修正,这使得 C++11 更像是从 C++98/03 中孕育出的一种新语言 。相比较而言, C++11 能更好地用于系统开发和库开发、语法更加泛华和简单化、更加稳定和安全,不仅功能更 强大,而且能提升程序员的开发效率,公司实际项目开发中也用得比较多,所以我们要作为一个 重点去学习 C++11 增加的语法特性非常篇幅非常多,我们这里没办法一 一讲解,所以本节课程主要讲解实际中比较实用的语法。

统一的列表初始化

{}初始化

C++98 中,标准允许使用花括号 {} 对数组或者结构体元素进行统一的列表初始值设定。比如:

C++11 扩大了用大括号括起的列表 ( 初始化列表 ) 的使用范围,使其可用于所有的内置类型和用户自
定义的类型, 使用初始化列表时,可添加等号 (=) ,也可不添加

 创建对象时也可以使用列表初始化方式调用构造函数初始化

class Date
{
public:
 Date(int year, int month, int day)
 :_year(year)
 ,_month(month)
 ,_day(day)
 {
 cout << "Date(int year, int month, int day)" << endl;
 }
private:
 int _year;
 int _month;
 int _day;
};
int main()
{
 Date d1(2022, 1, 1); // old style
 // C++11支持的列表初始化,这里会调用构造函数初始化
 Date d2{ 2022, 1, 2 };
 Date d3 = { 2022, 1, 3 };
//这里先生成一个初始化的临时对象,然后拷贝构造给对象
 return 0;
}

单参数列表初始化可省略列表

class A
{
public:
	//explicit A(int x, int y)   explicit可以防止隐式类型转换,使列表初始化失效
	A(int x, int y)
		:_x(x)
		,_y(y)
	{}

	A(int x)
		:_x(x)
		,_y(x)
	{}
private:
	int _x;
	int _y;
};

int main()
{

A aa1 = 1;
A aa2={1};

  return 0;  
}

std::initializer_list

std::initializer_list 是什么类型

std::initializer_list 使用场景
std::initializer_list 一般是作为构造函数的参数, C++11 STL 中的不少容器就增加
std::initializer_list 作为参数的构造函数,这样初始化容器对象就更方便了。也可以作为 operator=
的参数,这样就可以用大括号赋值
int main()
{
 vector<int> v = { 1,2,3,4 };
 list<int> lt = { 1,2 };
 // 1.这里{"sort", "排序"}会先初始化构造一个pair对象
 // 2.initializer_list<pair>的构造
 map<string, string> dict = { {"sort", "排序"}, {"insert", "插入"} };
// 使用大括号对容器赋值
v = {10, 20, 30};
 return 0;
}
让模拟实现的 vector 也支持 {} 初始化和赋值
namespace bit
{
template<class T>
class vector {
public:
     typedef T* iterator;
     vector(initializer_list<T> l)
     {
         _start = new T[l.size()];
         _finish = _start + l.size();
         _endofstorage = _start + l.size();
         iterator vit = _start;
         typename initializer_list<T>::iterator lit = l.begin();
         while (lit != l.end())
         {
             *vit++ = *lit++;
         }
         //for (auto e : l)
         //   *vit++ = e;
     }
     vector<T>& operator=(initializer_list<T> l) {
         vector<T> tmp(l);
         std::swap(_start, tmp._start);
         std::swap(_finish, tmp._finish);
         std::swap(_endofstorage, tmp._endofstorage);
         return *this;
     }
private:
     iterator _start;
     iterator _finish;
     iterator _endofstorage;
 };
}

声明

c++11 提供了多种简化声明的方式,尤其是在使用模板时。

auto

C++98 auto 是一个存储类型的说明符,表明变量是局部自动存储类型,但是局部域中定义局
部的变量默认就是自动存储类型,所以 auto 就没什么价值了。 C++11 中废弃 auto 原来的用法,将
其用于实现自动类型推断。这样要求必须进行显示初始化,让编译器将定义对象的类型设置为初
始化值的类型。具体看前文。

decltype

关键字 decltype 将变量的类型声明为表达式指定的类型。
template<class T>
class B
{
public:
	T* New(int n)
	{
		return new T[n];
	}
};


auto func1()
{
	list<int> lt;
	auto ret = lt.begin();

	return ret;
}

int main()
{
	list<int>::iterator it1;
	
		// typeid推出时一个单纯的字符串
				cout << typeid(it1).name() << endl;
			//	// 不能用来定义对象
			//	//typeid(it1).name() it2;
			
				// 可以用来定义对象
				decltype(it1) it2;
				cout << typeid(it2).name() << endl;
			
				auto it3 = it1;
				cout << typeid(it3).name() << endl;
		    
				auto ret3 = func1();
				B<decltype(ret3)> bb1;
			
			
				B<decltype(it3)> bb2;
				//B<std::list<int>::iterator> bb2;
				// auto和decltype有些地方增加代码读起来难度
			
				return 0;

}

nullptr

由于 C++ NULL 被定义成字面量 0 ,这样就可能回带来一些问题,因为 0 既能指针常量,又能表示 整形常量。所以出于清晰和安全的角度考虑,C++11 中新增了 nullptr ,用于表示空指针

范围for循环

在前文我们已经具体讲解了,这里我们补充一点

int main()
{
	map<string, string> dict2 = { {"sort", "排序"}, {"insert", "插入"} };
	for (auto& [x,y] : dict2)
	{
		cout << x << ":" << y << endl;
		//x += '1';
		y += '2';
	}

	for (auto [x, y] : dict2)
	{
		cout << x << ":" << y << endl;
	}

	pair<string, string> kv1 = { "sort", "排序" };
	auto [x, y] = kv1;

	return 0;
}

智能指针

这个我们在智能指针课程中已经会进行了非常详细的讲解,这里就不进行讲解了

STL中一些变化

新容器
用橘色圈起来是 C++11 中的一些几个新容器,但是实际最有用的是 unordered_map 和 unordered_set。这两个我们前面已经进行了非常详细的讲解,其他的大家了解一下即可。

容器中的一些新方法
如果我们再细细去看会发现基本每个容器中都增加了一些 C++11 的方法,但是其实很多都是用得
比较少的。
比如提供了 cbegin cend 方法返回 const 迭代器等等,但是实际意义不大,因为 begin end 也是
可以返回 const 迭代器的,这些都是属于锦上添花的操作。
实际上 C++11 更新后,容器中增加的新方法最后用的插入接口函数的右值引用版本:

http://www.cplusplus.com/reference/vector/vector/emplace_back/

http://www.cplusplus.com/reference/vector/vector/push_back/

http://www.cplusplus.com/reference/map/map/insert/

http://www.cplusplus.com/reference/map/map/emplace/

右值引用和移动语义

左值引用和右值引用
传统的 C++ 语法中就有引用的语法,而 C++11 中新增了的右值引用语法特性,所以从现在开始我们
之前学习的引用就叫做左值引用。 无论左值引用还是右值引用,都是给对象取别名

什么是左值?什么是左值引用?
左值是一个表示数据的表达式 ( 如变量名或解引用的指针 ) 我们可以获取它的地址 + 可以对它赋
值,左值可以出现赋值符号的左边,右值不能出现在赋值符号左边 。定义时 const 修饰符后的左
值,不能给他赋值,但是可以取它的地址。左值引用就是给左值的引用,给左值取别名。

什么是右值?什么是右值引用?
右值也是一个表示数据的表达式,如:字面常量、表达式返回值,函数返回值 ( 这个不能是左值引 用返回) 等等, 右值可以出现在赋值符号的右边,但是不能出现出现在赋值符号的左边,右值不能 取地址 。右值引用就是对右值的引用,给右值取别名。

需要注意的是右值是不能取地址的,但是给右值取别名后,会导致右值被存储到特定位置,且可
以取到该位置的地址,也就是说例如:不能取字面量10的地址,但是rr1引用后,可以对rr1取地
址,也可以修改rr1。如果不想rr1被修改,可以用const int&& rr1 去引用。

我的总结:

左值:可以取地址的

右值:不可以取地址的,分为内置类型字面常量,匿名对象/变量,临时对象/变量

左值和右值都存在地址,只是左值能取地址,而右值不能取地址

右值分为纯右值(字面常量)和将亡值(匿名对象/变量,临时对象/变量)

个人猜测:右值引用引用字面常量时,会生成临时变量/对象

int&& p=10;// int b=10; int&& p= b;  b是临时变量

class A
{
public:
    A(int a1, int a2)
        :_a1(a1)
        , _a2(a2)
    {}

private:
    int _a1;
    int _a2;
};

A&& p = { 1,2 };// A b(1,2); A&& p= b; b是临时对象

左值引用与右值引用比较

左值引用总结:
1. 左值引用只能引用左值,不能引用右值。
2. 但是 const 左值引用既可引用左值,也可引用右值

个人猜测:const int& ra3 =10;// int b=10;const int& ra3 = b; 

右值引用总结:
1. 右值引用只能右值,不能引用左值。
2. 但是右值引用可以 move 以后的左值。

个人猜测:move()是将左值变成右值的临时变量。

右值引用使用场景和意义

前面我们可以看到左值引用既可以引用左值和又可以引用右值,那为什么 C++11 还要提出右值引
用呢?是不是化蛇添足呢?下面我们来看看左值引用的短板,右值引用是如何补齐这个短板的!
namespace bit
{
	class string
	{
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(_size)
		{
			cout << "string(char* str) -- 构造" << endl;

			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		// s1.swap(s2)
		void swap(string& ss)
		{
			::swap(_str, ss._str);
			::swap(_size, ss._size);
			::swap(_capacity, ss._capacity);
		}

		// 拷贝构造
		// 左值
		string(const string& s)
		{
			cout << "string(const string& s) -- 深拷贝" << endl;

			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}

		// 移动构造  -- 移动将亡值对象的资源
		// 右值(将亡值)
		string(string&& s)		
		{
			cout << "string(string&& s) -- 移动构造" << endl;
			swap(s);
		}

		// 赋值重载
		// s3 = 左值
		string& operator=(const string& s)
		{
			cout << "string& operator=(string s) -- 深拷贝" << endl;
			char* tmp = new char[s._capacity + 1];
			strcpy(tmp, s._str);

			delete[] _str;
			_str = tmp;
			_size = s._size;
			_capacity = s._capacity;

			return *this;
		}

		// s3 = 将亡值
		string& operator=(string&& s)
		{
			cout << "string(string&& s) -- 移动赋值" << endl;
			swap(s);

			return *this;
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;

				_capacity = n;
			}
		}

		void push_back(char ch)
		{
			if (_size >= _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newcapacity);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}

		//string operator+=(char ch)
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

		const char* c_str() const
		{
			return _str;
		}
	private:
		char* _str = nullptr;
		size_t _size = 0;
		size_t _capacity = 0; // 不包含最后做标识的\0
	};

	bit::string to_string(int value)
	{
		bool flag = true;
		if (value < 0)
		{
			flag = false;
			value = 0 - value;
		}

		bit::string str;
		while (value > 0)
		{
			int x = value % 10;
			value /= 10;

			str += ('0' + x);
		}

		if (flag == false)
		{
			str += '-';
		}

		std::reverse(str.begin(), str.end());

		// return move(str);
		return str;
	}
}

左值引用的短板

但是当函数返回对象是一个局部变量,出了函数作用域就不存在了,就不能使用左值引用返回,
只能传值返回。例如: bit::string to_string(int value) 函数中可以看到,这里只能使用传值返回,
传值返回会导致至少 1 次拷贝构造 ( 如果是一些旧一点的编译器可能是两次拷贝构造 )
namespace bit
{
 bit::string to_string(int value)
 {
 bool flag = true;
 if (value < 0)
 {
 flag = false;
 value = 0 - value;
 }
 bit::string str;
 while (value > 0)
 {
 int x = value % 10;
 value /= 10;
 str += ('0' + x);
 }
 if (flag == false)
 {
 str += '-';
 }

std::reverse(str.begin(), str.end());
 return str;
 }
}
int main()
{
// 在bit::string to_string(int value)函数中可以看到,这里
// 只能使用传值返回,传值返回会导致至少1次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)。
 bit::string ret1 = bit::to_string(1234);
 bit::string ret2 = bit::to_string(-1234);
 return 0;
}

或者这样

右值引用和移动语义解上述问题

bit::string 中增加移动构造, 移动构造本质是将参数右值的资源窃取过来,占位已有,那么就不
用做深拷贝了,所以它叫做移动构造,就是窃取别人的资源来构造自己
// 移动构造
string(string&& s)
 :_str(nullptr)
 ,_size(0)
 ,_capacity(0)
{
 cout << "string(string&& s) -- 移动语义" << endl;
 swap(s);
}
int main()
{
 bit::string ret2 = bit::to_string(-1234);
 return 0;
}
再运行上面bit::to_string的两个调用,我们会发现,这里没有调用深拷贝的拷贝构造,而是调用
了移动构造,移动构造中没有新开空间,拷贝数据,所以效率提高了。

这里直接将左值str当成右值去用,编译器默认加了个move(str);

不仅仅有移动构造,还有移动赋值:
bit::string 类中增加移动赋值函数,再去调用 bit::to_string(1234) ,不过这次是将
bit::to_string(1234) 返回的右值对象赋值给 ret1 对象,这时调用的是移动构造。
// 移动赋值
string& operator=(string&& s)
{
cout << "string& operator=(string&& s) -- 移动语义" << endl;
swap(s);
return *this;
}
int main()
{
 bit::string ret1;
 ret1 = bit::to_string(1234);
 return 0;
}
// 运行结果:
// string(string&& s) -- 移动语义
// string& operator=(string&& s) -- 移动语义
这里运行后,我们看到调用了一次移动构造和一次移动赋值。因为如果是用一个已经存在的对象接收,编译器就没办法优化了。bit::to_string 函数中会先用 str 生成构造生成一个临时对象,但是我们可以看到,编译器很聪明的在这里把str 识别成了右值,调用了移动构造。然后在把这个临时对象做为bit::to_string 函数调用的返回值赋值给 ret1 ,这里调用的移动赋值。

STL 中的容器都是增加了移动构造和移动赋值:

http://www.cplusplus.com/reference/string/string/string/

http://www.cplusplus.com/reference/vector/vector/vector/

右值引用本身是左值

int main()
{
	std::string s3("22222222222");
	// 左值引用
	std::string& s4 = s3;
	cout << &s4 << endl;

	// 右值引用
	std::string&& s1 = std::string("111111111");
	// s1是左值(右值引用本身是左值)
	cout << &s1 << endl;
	//cout << &std::string("111111111") << endl;

	std::string& s5 = s1;

	std::string&& s6 = std::string("111111111111111111111111111111111111111");
	std::string& s7 = s6;

	return 0;
}

右值引用本身是左值,只有左值才能取地址,这样才能使用右值的资源

右值引用引用左值及其一些更深入的使用场景分析

按照语法,右值引用只能引用右值,但右值引用一定不能引用左值吗?因为:有些场景下,可能真的需要用右值去引用左值实现移动语义。当需要用右值引用引用一个左值时,可以通过 move 函数将左值转化为右值 C++11 中, std::move() 函数 位于 头文件中,该函数名字具有迷惑性,它并不搬移任何东西,唯一的功能就是将一个左值强制转化为右值引用,然后实现移动语义
template<class _Ty>
inline typename remove_reference<_Ty>::type&& move(_Ty&& _Arg) _NOEXCEPT
{
// forward _Arg as movable
 return ((typename remove_reference<_Ty>::type&&)_Arg);
}
int main()
{
 bit::string s1("hello world");
 // 这里s1是左值,调用的是拷贝构造
 bit::string s2(s1);
 // 这里我们把s1 move处理以后, 会被当成右值,调用移动构造
 // 但是这里要注意,一般是不要这样用的,因为我们会发现s1的
 // 资源被转移给了s3,s1被置空了。
 bit::string s3(std::move(s1));
 return 0;
}
STL 容器插入接口函数也增加了右值引用版本:

http://www.cplusplus.com/reference/list/list/push_back/

http://www.cplusplus.com/reference/vector/vector/push_back/

void push_back (value_type&& val);
int main()
{
 list<bit::string> lt;
 bit::string s1("1111");
// 这里调用的是拷贝构造
 lt.push_back(s1);
// 下面调用都是移动构造
 lt.push_back("2222");
 lt.push_back(std::move(s1));
 return 0;
}
运行结果:
// string(const string& s) -- 深拷贝
// string(string&& s) -- 移动语义
// string(string&& s) -- 移动语义

完美转发

模板中的 && 万能引用
void Fun(int &x){ cout << "左值引用" << endl; }
void Fun(const int &x){ cout << "const 左值引用" << endl; }
void Fun(int &&x){ cout << "右值引用" << endl; }
void Fun(const int &&x){ cout << "const 右值引用" << endl; }

// 模板中的&&不代表右值引用,而是万能引用,其既能接收左值又能接收右值。
// 模板的万能引用只是提供了能够接收同时接收左值引用和右值引用的能力,
// 但是引用类型的唯一作用就是限制了接收的类型,后续使用中都退化成了左值,
// 我们希望能够在传递过程中保持它的左值或者右值的属性, 就需要用我们下面学习的完美转发
template<typename T>
void PerfectForward(T&& t)
{
 Fun(t);
}
int main()
{
 PerfectForward(10);           // 左值
 int a;
 PerfectForward(a);            // 左值
 PerfectForward(std::move(a)); // 左值
 const int b = 8;
 PerfectForward(b);      // const 左值
 PerfectForward(std::move(b)); // const 左值
 return 0;
}
std::forward 完美转发在传参的过程中保留对象原生类型属性
void Fun(int &x){ cout << "左值引用" << endl; }
void Fun(const int &x){ cout << "const 左值引用" << endl; }
void Fun(int &&x){ cout << "右值引用" << endl; }
void Fun(const int &&x){ cout << "const 右值引用" << endl; }
// std::forward<T>(t)在传参的过程中保持了t的原生类型属性。
template<typename T>
void PerfectForward(T&& t)
{
 Fun(std::forward<T>(t));
}
int main()
{
 PerfectForward(10);           // 右值
 int a;
 PerfectForward(a);            // 左值
 PerfectForward(std::move(a)); // 右值
 const int b = 8;
 PerfectForward(b);      // const 左值
 PerfectForward(std::move(b)); // const 右值
 return 0;
}

类似下面这种效果:

void Fun(int& x) { cout << "左值引用" << endl; }
void Fun(const int& x) { cout << "const 左值引用" << endl; }

void Fun(int&& x) { cout << "右值引用" << endl; }
void Fun(const int&& x) { cout << "const 右值引用" << endl; }


template<typename T>
void PerfectForward(T&& t)
{
	//Fun((T&&)t);
	Fun(forward<T>(t));
}

void PerfectForward(int&& t)
{
	Fun((int&&)t);
}

void PerfectForward(int& t)
{
	Fun((int&)t);
}

void PerfectForward(const int&& t)
{
	Fun((const int&&)t);
}

void PerfectForward(const int& t)
{
	Fun((const int&)t);
}
完美转发实际中的使用场景:
template<class T>
struct ListNode
{
 ListNode* _next = nullptr;
 ListNode* _prev = nullptr;
 T _data;
};
template<class T>
class List
{
 typedef ListNode<T> Node;
public:
 List()
 {
 _head = new Node;
 _head->_next = _head;
 _head->_prev = _head;
 }
 void PushBack(T&& x)
 {
 //Insert(_head, x);
 Insert(_head, std::forward<T>(x));
 }
 void PushFront(T&& x)
 {
 //Insert(_head->_next, x);
 Insert(_head->_next, std::forward<T>(x));
 }
 void Insert(Node* pos, T&& x)
 {
 Node* prev = pos->_prev;
 Node* newnode = new Node;
 newnode->_data = std::forward<T>(x); // 关键位置
 // prev newnode pos
 prev->_next = newnode;
 newnode->_prev = prev;
 newnode->_next = pos;
 pos->_prev = newnode;
 }
 void Insert(Node* pos, const T& x)
 {
 Node* prev = pos->_prev;
 Node* newnode = new Node;
 newnode->_data = x; // 关键位置
 // prev newnode pos
 prev->_next = newnode;
newnode->_prev = prev;
 newnode->_next = pos;
 pos->_prev = newnode;
 }
private:
 Node* _head;
};
int main()
{
 List<bit::string> lt;
 lt.PushBack("1111");
 lt.PushFront("2222");
 return 0;
}

lambda表达式

C++98 中,如果想要对一个数据集合中的元素进行排序,可以使用 std::sort 方法
#include <algorithm>
#include <functional>
int main()
{
int array[] = {4,1,8,5,3,7,0,9,2,6};
// 默认按照小于比较,排出来结果是升序
std::sort(array, array+sizeof(array)/sizeof(array[0]));
// 如果需要降序,需要改变元素的比较规则
std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
return 0;
}
如果待排序元素为自定义类型,需要用户定义排序时的比较规则:
struct Goods
{
 string _name;  // 名字
 double _price; // 价格
 int _evaluate; // 评价
 Goods(const char* str, double price, int evaluate)
 :_name(str)
 , _price(price)
 , _evaluate(evaluate)
 {}
};
struct ComparePriceLess
{
 bool operator()(const Goods& gl, const Goods& gr)
 {
 return gl._price < gr._price;
}
};
struct ComparePriceGreater
{
 bool operator()(const Goods& gl, const Goods& gr)
 {
 return gl._price > gr._price;
 }
};
int main()
{
 vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 
3 }, { "菠萝", 1.5, 4 } };
 sort(v.begin(), v.end(), ComparePriceLess());
sort(v.begin(), v.end(), ComparePriceGreater());
}
随着 C++ 语法的发展, 人们开始觉得上面的写法太复杂了,每次为了实现一个 algorithm 算法,
都要重新去写一个类,如果每次比较的逻辑不一样,还要去实现多个类,特别是相同类的命名,
这些都给编程者带来了极大的不便 。因此,在 C++11 语法中出现了 Lambda 表达式。

 lambda表达式

上述代码就是使用 C++11 中的 lambda 表达式来解决,可以看出 lambda 表达式实际是一个匿名函 数。
int main()
{
	vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2,3 }, { "菠萝", 1.5, 4 } };

	sort(v.begin(), v.end(), ComparePriceLess());
	sort(v.begin(), v.end(), ComparePriceGreater());


	auto priceLess = [](const Goods& g1, const Goods& g2)
	{
		return g1._price < g2._price;
	};
	sort(v.begin(), v.end(), priceLess);

	cout << typeid(priceLess).name() << endl;

	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) 
 		{
			return g1._price > g2._price;
		});

	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2)
		{
			return g1._evaluate < g2._evaluate;
		});

	sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2)
		{
			return g1._evaluate > g2._evaluate;
		});
  	return 0;
}
lambda 表达式语法
lambda 表达式书写格式:
[capture-list] (parameters) mutable -> return-type { statement }
1. lambda 表达式各部分说明
  • [capture-list] : 捕捉列表,该列表总是出现在lambda函数的开始位置,编译器根据[]判断接下来的代码是否为lambda函数捕捉列表能够捕捉上下文中的变量供lambda函数使用
  • (parameters):参数列表。与普通函数的参数列表一致,如果不需要参数传递,则可以连同()一起省略
  • mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量性。使用该修饰符时,参数列表不可省略(即使参数为空)
  • ->returntype:返回值类型。用追踪返回类型形式声明函数的返回值类型,没有返回值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推
  • {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获到的变量。
注意:
lambda 函数定义中, 参数列表和返回值类型都是可选部分,而捕捉列表和函数体可以为
。因此 C++11 最简单的 lambda 函数为: []{} ; lambda 函数不能做任何事情。
int main()
{
	// lambda
	auto add1 = [](int a, int b)->int {return a + b; };
	// 返回值可以省略
	auto add2 = [](int a, int b) {return a + b; };
	// 没有参数,参数列表可以省略
	auto func1 = [] {cout << "hello world" << endl; };

	cout << typeid(add1).name() << endl;
	cout << typeid(add2).name() << endl;
	cout << typeid(func1).name() << endl;

	cout << add1(1, 2) << endl;
	func1();

	return 0;
}

通过上述例子可以看出,lambda表达式实际上可以理解为无名函数,该函数无法直接调用,如果想要直接调用,可借助auto将其赋值给一个变量。
实际在底层编译器对于lambda表达式的处理方式,完全就是按照函数对象的方式处理的,即:如
果定义了一个lambda表达式,编译器会自动生成一个类,在该类中重载了operator()。

2.捕获列表说明
捕捉列表描述了上下文中那些数据可以被 lambda 使用 ,以及 使用的方式传值还是传引用
[var] :表示值传递方式捕捉变量 var
[=] :表示值传递方式捕获所有父作用域中的变量 ( 包括 this)
[&var] :表示引用传递捕捉变量 var
[&] :表示引用传递捕捉所有父作用域中的变量 ( 包括 this)
[this] :表示值传递方式捕捉当前的 this 指针
注意:
a. 父作用域指包含 lambda 函数的语句块
b. 语法上捕捉列表可由多个捕捉项组成,并以逗号分割
比如: [=, &a, &b] :以引用传递的方式捕捉变量 a b ,值传递方式捕捉其他所有变量
[& a, this] :值传递方式捕捉变量 a this ,引用方式捕捉其他变量
c. 捕捉列表不允许变量重复传递,否则就会导致编译错误
比如: [=, a] = 已经以值传递方式捕捉了所有变量,捕捉 a 重复
d. 在块作用域以外的 lambda 函数捕捉列表必须为空
e. 在块作用域中的 lambda 函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域或者
非局部变量都会导致编译报错。
f. lambda 表达式之间不能相互赋值 ,即使看起来类型相同

 [var]:表示值传递方式捕捉变量var,加mutable才能修改捕捉变量,外面不修改

 //捕捉a b对象给lambda
	// mutable可以修改传值捕捉对象(日常一般不需要)
	// 因为a b是拷贝过来,虽然修改也不改变外面的a b
	auto swap2 = [a, b]() mutable
	{
		int tmp = a;
		a = b;
		b = tmp;
	};

[&var]:表示引用传递捕捉变量var,外值一定改变

 引用方式捕捉
	auto swap3 = [&a, &b]()
	{
		int tmp = a;
		a = b;
		b = tmp;
	};

    同理

int* pa = &a, * pb = &b;

	auto swap4 = [pa, pb]()
	{
		int tmp = *pa;
		*pa = *pb;
		*pb = tmp;
	};

[=]:表示值传递方式捕获所有父作用域中的变量(包括this)

int a = 1, b = 2, c = 3, d = 4, e = 5;
	// 传值捕捉所有对象
	auto func1 = [=]()
	{
		return a + b + c * d;
    };

[&]:表示引用传递捕捉所有父作用域中的变量(包括this)

 //传引用捕捉所有对象
	auto func2 = [&]()
	{
		a++;
		b++;
		c++;
		d++;
		e++;
	};

混合捕捉

// 混合捕捉,传引用捕捉所有对象,但是d和e传值捕捉
	auto func3 = [&, d, e]()
	{
		a++;
		b++;
		c++;
		//d++;
		//e++;
	};
 //a b传引用捕捉,d和e传值捕捉
 auto func4 = [&a, &b, d, e]() mutable
	{
		a++;
		b++;
		d++;
		e++;
	};

新的类功能

默认成员函数
原来 C++ 类中,有 6 个默认成员函数:
1. 构造函数
2. 析构函数
3. 拷贝构造函数
4. 拷贝赋值重载
5. 取地址重载
6. const 取地址重载
最后重要的是前 4 个,后两个用处不大。默认成员函数就是我们不写编译器会生成一个默认的。
C++11 新增了两个:移动构造函数和移动赋值运算符重载
针对移动构造函数和移动赋值运算符重载有一些需要注意的点如下:
如果你没有自己实现移动构造函数,且没有实现析构函数 、拷贝构造、拷贝赋值重载中的任
意一个。那么编译器会自动生成一个默认移动构造。默认生成的移动构造函数,对于内置类
型成员会执行逐成员按字节拷贝,自定义类型成员,则需要看这个成员是否实现移动构造,
如果实现了就调用移动构造,没有实现就调用拷贝构造。
如果你没有自己实现移动赋值重载函数,且没有实现析构函数 、拷贝构造、拷贝赋值重载中
的任意一个,那么编译器会自动生成一个默认移动赋值。默认生成的移动构造函数,对于内
置类型成员会执行逐成员按字节拷贝,自定义类型成员,则需要看这个成员是否实现移动赋
值,如果实现了就调用移动赋值,没有实现就调用拷贝赋值。 ( 默认移动赋值跟上面移动构造
完全类似 )
如果你提供了移动构造或者移动赋值,编译器不会自动提供拷贝构造和拷贝赋值。

默认提供的只支持浅拷贝,实现其中一个代表实现深拷贝,所以就不提供默认。 

强制生成默认函数的关键字default:

C++11 可以让你更好的控制要使用的默认函数。假设你要使用某个默认的函数,但是因为一些原 因这个函数没有默认生成。比如:我们提供了拷贝构造,就不会生成移动构造了,那么我们可以 使用default 关键字显示指定移动构造生成。
class Person
{
public:
	Person(const char* name = "张三", int age = 18)
		:_name(name)
		, _age(age)
	{}
	
	// 强制生成
	Person(const Person& p) = default;
	Person& operator=(const Person & p) = default;
	Person(Person&& p) = default;
	Person& operator=(Person&& p) = default;

	~Person()
	{}
private:
	bit::string _name;
	int _age;
};

int main()
{
	Person s1;
	Person s2 = s1; // 默认拷贝构造

	Person s3 = std::move(s1); // 默认移动构造

	Person s4;
	s4 = std::move(s2); // 默认移动赋值

	return 0;
}

禁止生成默认函数的关键字delete:

如果能想要限制某些默认函数的生成,在 C++98 中,是该函数设置成 private ,并且只声明补丁 已,这样只要其他人想要调用就会报错。在C++11 中更简单,只需在该函数声明加上 =delete 即 可,该语法指示编译器不生成对应函数的默认版本,称=delete 修饰的函数为删除函数。
// 这个类只能在堆上生成对象
class HeapOnly
{
public:
	static HeapOnly* CreateObj()
	{
		return new HeapOnly;
	}

	// C++11
	HeapOnly(const HeapOnly&) = delete;

	// C++98 私有+只声明不实现
private:
	HeapOnly(const HeapOnly&);

	HeapOnly()
	{}

	int _a = 1;
};
 
int main()
{
	//HeapOnly ho1;
	//HeapOnly* p1 = new HeapOnly;
	HeapOnly* p2 = HeapOnly::CreateObj();

	// 不能被拷贝,才能禁止
	//HeapOnly obj(*p2);

	return 0;
}

继承和多态中的finaloverride关键字

这个我们在继承和多态章节已经进行了详细讲解这里就不再细讲,需要的话去复习继承和多台章
节吧

可变参数模板

C++11 的新特性可变参数模板能够让您创建可以接受可变参数的函数模板和类模板,相比 C++98/03,类模版和函数模版中只能含固定数量的模版参数,可变模版参数无疑是一个巨大的改 进。然而由于可变模版参数比较抽象,使用起来需要一定的技巧,所以这块还是比较晦涩的。现 阶段呢,我们掌握一些基础的可变参数模板特性就够我们用了,所以这里我们点到为止,以后大 家如果有需要,再可以深入学习。

上面的参数 args 前面有省略号,所以它就是一个可变模版参数,我们把带省略号的参数称为 参数 包” ,它里面包含了 0 N N>=0 )个模版参数。我们无法直接获取参数包 args 中的每个参数的, 只能通过展开参数包的方式来获取参数包中的每个参数,这是使用可变模版参数的一个主要特 点,也是最大的难点,即如何展开可变模版参数。由于语法不支持使用args[i] 这样方式获取可变参数,所以我们的用一些奇招来一一获取参数包的值。

// C printf 只能打印内置类型
// C++打印任意类型对象的可变参数函数呢
template <class ...Args>
void Cpp_Printf(Args... args)
{
	// 计算参数包的数据个数
	cout << sizeof...(args) << endl;
}

int main()
{
	Cpp_Printf(1);//1
	Cpp_Printf(1, 'A');//2
	Cpp_Printf(1, 'A', std::string("sort"));//3

	return 0;
}

递归函数方式展开参数包
// 编译时,参数推到递归
void _Cpp_Printf()
{
	cout << endl;
}

template <class T, class ...Args>
void _Cpp_Printf(const T& val, Args... args)
{
	cout << val << endl;

	_Cpp_Printf(args...);
}

template <class ...Args>
void Cpp_Printf(Args... args)
{
	_Cpp_Printf(args...);
}

int main()
{
	Cpp_Printf(1.1);
	Cpp_Printf(1.1, 'x');
	Cpp_Printf(1, 'A', std::string("sort"));

	return 0;
}

数组构造程展开参数包
template <class T>
int PrintArg(T t)
{
	cout << t << " ";
	return 0;
}

template <class ...Args>
void Cpp_Printf(Args... args)
{
	// 编译时推导,args...参数有几个值,PrintArg就调用几次,就有几个返回值,arr就开多大
	int arr[] = { PrintArg(args)... };
	cout << endl;
}

//void Cpp_Printf(int x, char y, std::string z)
//{
//	int arr[] = { PrintArg(x),PrintArg(y),PrintArg(z) };
//	cout << endl;
//}

int main()
{
	Cpp_Printf(1.1);
	Cpp_Printf(1.1, 'x');
	Cpp_Printf(1, 'A', std::string("sort"));

	return 0;
}

STL 容器中的 empalce 相关接口函数:

http://www.cplusplus.com/reference/vector/vector/emplace_back/

http://www.cplusplus.com/reference/list/list/emplace_back/

首先我们看到的 emplace 系列的接口,支持模板的可变参数,并且万能引用。那么相对 insert 和 emplace系列接口的优势到底在哪里呢?
    // 没区别
	bit::list<pair<bit::string, int>> lt;

	pair<bit::string, int> kv1("xxxxx", 1);//构造
	//lt.push_back(kv1);//深拷贝
	lt.push_back(move(kv1));//移动构造

	cout << endl;

	// 直接传pair的对象效果跟push_back系列是一样的
	pair<bit::string, int> kv2("xxxxx", 1);//构造 
	lt.emplace_back(kv2);//深拷贝
	lt.emplace_back(move(kv2));//移动构造

	// 直接传构造pair的参数包,参数包一直往下传,底层直接构造
	lt.emplace_back("xxxxx", 1);//构造

List单链表模拟加入emplace_back初始化

namespace bit
{
	template<class T>
	struct ListNode
	{
		ListNode<T>* _next;
		ListNode<T>* _prev;
		T _data;

		ListNode(const T& x = T())
			:_next(nullptr)
			,_prev(nullptr)
			,_data(x)
		{}

		ListNode(T&& x)
			:_next(nullptr)
			, _prev(nullptr)
			, _data(forward<T>(x))
		{}

		template <class... Args>
		ListNode(Args&&... args)
			:_next(nullptr)
			, _prev(nullptr)
			, _data(forward<Args>(args)...)
		{}
		
		/*ListNode(const char* str, int val)
			: _next(nullptr)
			, _prev(nullptr)
			, _data(str, val)
		{}*/
	};

	// typedef ListIterator<T, T&, T*> iterator;
	// typedef ListIterator<T, const T&, const T*> const_iterator;

	template<class T, class Ref, class Ptr>
	struct ListIterator
	{
		typedef ListNode<T> Node;
		typedef ListIterator<T, Ref, Ptr> Self;

		Node* _node;

		ListIterator(Node* node)
			:_node(node)
		{}

		// *it
		//T& operator*()
		Ref operator*()
		{
			return _node->_data;
		}
		
		// it->
		//T* operator->()
		Ptr operator->()
		{
			return &_node->_data;
		}

		// ++it
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		Self operator++(int)
		{
			Self tmp(*this);
			_node = _node->_next;

			return tmp;
		}

		Self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}

		Self operator--(int)
		{
			Self tmp(*this);
			_node = _node->_prev;

			return tmp;
		}

		bool operator!=(const Self& it)
		{
			return _node != it._node;
		}

		bool operator==(const Self& it)
		{
			return _node == it._node;
		}
	};

	//template<class T>
	//struct ListConstIterator
	//{
	//	typedef ListNode<T> Node;
	//	typedef ListConstIterator<T> Self;

	//	Node* _node;

	//	ListConstIterator(Node* node)
	//		:_node(node)
	//	{}

	//	// *it
	//	const T& operator*()
	//	{
	//		return _node->_data;
	//	}

	//	// it->
	//	const T* operator->()
	//	{
	//		return &_node->_data;
	//	}

	//	// ++it
	//	Self& operator++()
	//	{
	//		_node = _node->_next;
	//		return *this;
	//	}

	//	Self operator++(int)
	//	{
	//		Self tmp(*this);
	//		_node = _node->_next;

	//		return tmp;
	//	}

	//	Self& operator--()
	//	{
	//		_node = _node->_prev;
	//		return *this;
	//	}

	//	Self operator--(int)
	//	{
	//		Self tmp(*this);
	//		_node = _node->_prev;

	//		return tmp;
	//	}

	//	bool operator!=(const Self& it)
	//	{
	//		return _node != it._node;
	//	}

	//	bool operator==(const Self& it)
	//	{
	//		return _node == it._node;
	//	}
	//};

	template<class T>
	class list
	{
		typedef ListNode<T> Node;
	public:
		//typedef ListIterator<T> iterator;
		//typedef ListConstIterator<T> const_iterator;

		typedef ListIterator<T, T&, T*> iterator;
		typedef ListIterator<T, const T&, const T*> const_iterator;

		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

		// const迭代器,需要是迭代器不能修改,还是迭代器指向的内容?
		// 迭代器指向的内容不能修改!const iterator不是我们需要const迭代器

		// T* const p1
		// const T* p2
		const_iterator begin() const
		{
			return _head->_next;
		}

		const_iterator end() const
		{
			return _head;
		}

		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;

			_size = 0;
		}

		list()
		{
			empty_init();
		}

		list(initializer_list<T> il)
		{
			empty_init();

			for (auto& e : il)
			{
				push_back(e);
			}
		}


		// lt2(lt1)
		list(const list<T>& lt)
		{
			empty_init();
			for (auto& e : lt)
			{
				push_back(e);
			}
		}

		// 需要析构,一般就需要自己写深拷贝
		// 不需要析构,一般就不需要自己写深拷贝,默认浅拷贝就可以

		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
			std::swap(_size, lt._size);
		}

		// lt1 = lt3
		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}

		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}

		/*void push_back(const T& x)
		{
			Node* newnode = new Node(x);
			Node* tail = _head->_prev;

			tail->_next = newnode;
			newnode->_prev = tail;
			newnode->_next = _head;
			_head->_prev = newnode;
		}*/

		void push_back(const T& x)
		{
			insert(end(), x);
		}

		void push_back(T&& x)
		{
			insert(end(), forward<T>(x));
		}

		template <class... Args>
		void emplace_back(Args&&... args)
		{
			emplace(end(), forward<Args>(args)...);
		}

		/*void emplace_back(const char* str, int val)
		{
			emplace(end(), str, val);
		}*/

		void push_front(const T& x)
		{
			insert(begin(), x);
		}

		void pop_back()
		{
			erase(--end());
		}

		void pop_front()
		{
			erase(begin());
		}

		void insert(iterator pos, const T& val)
		{
			Node* cur = pos._node;
			Node* newnode = new Node(val);
			Node* prev = cur->_prev;

			// prev newnode cur;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
		}

		void insert(iterator pos, T&& val)
		{
			Node* cur = pos._node;
			Node* newnode = new Node(forward<T>(val));
			Node* prev = cur->_prev;

			// prev newnode cur;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
		}

		template <class... Args>
		void emplace(iterator pos, Args&&... args)
		{
			Node* cur = pos._node;
			Node* newnode = new Node(forward<Args>(args)...);
			Node* prev = cur->_prev;

			// prev newnode cur;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
		}

		//void emplace(iterator pos, const char* str, int val)
		//{
		//	Node* cur = pos._node;
		//	Node* newnode = new Node(str, val);
		//	Node* prev = cur->_prev;
		//	//...
		//}

		iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* next = cur->_next;
			
			prev->_next = next;
			next->_prev = prev;
			delete cur;
			_size--;

			return iterator(next);
		}

		size_t size() const
		{
			return _size;
		}

		bool empty()
		{
			return _size == 0;
		}

	private:
		Node* _head;
		size_t _size;
	};

emplace参数包性能分析

包装器

function 包装器
function 包装器 也叫作适配器。 C++ 中的 function 本质是一个类模板,也是一个包装器。

ret = func(x);
// 上面func可能是什么呢?那么func可能是函数名?函数指针?函数对象(仿函数对象)?也有可能
//是lamber表达式对象?所以这些都是可调用的类型!如此丰富的类型,可能会导致模板的效率低下!
//为什么呢?我们继续往下看
template<class F, class T>
T useF(F f, T x)
{
 static int count = 0;
 cout << "count:" << ++count << endl;
 cout << "count:" << &count << endl;
 return f(x);
}


double f(double i)
{
 return i / 2;
}
struct Functor
{
 double operator()(double d)
 {
 return d / 3;
 }
};
int main()
{
 // 函数名
 cout << useF(f, 11.11) << endl;
 // 函数对象
 cout << useF(Functor(), 11.11) << endl;
 // lamber表达式
 cout << useF([](double d)->double{ return d/4; }, 11.11) << endl;
 return 0;
}
通过上面的程序验证,我们会发现 useF 函数模板实例化了三份。
包装器可以很好的解决上面的问题

#include<functional>


int f(int a, int b)
{
	return a + b;
}

struct Functor
{
public:
	int operator() (int a, int b)
	{
		return a + b;
	}
};

// 不是定义可调用对象,包装可调用对象
int main()
{
	function<int(int, int)> fc1;

    // 函数名(函数指针)
	//function<int(int, int)> fc2(f);
	function<int(int, int)> fc2 = f;
    cout << fc2(1, 2) << endl;
    //底层:cout << fc2.operator()(1, 2) << endl;

    // 函数对象
	function<int(int, int)> fc3 = Functor();
    cout << fc3(1, 2) << endl;

    // lamber表达式
	function<int(int, int)> fc4 = [](int x, int y) {return x + y;};
    cout << fc4(1, 2) << endl;
	

	return 0;
}

类函数成员包装

// 包装成员函数指针
class Plus
{
public:
	static int plusi(int a, int b)
	{
		return a + b;
	}

	double plusd(double a, double b)
	{
		return a + b;
	}
};

int main()
{
	// 成员函数的函数指针  &类型::函数名
	function<int(int, int)> fc1 = &Plus::plusi;
	cout << fc1(1, 2) << endl;

	function<double(Plus*, double, double)> fc2 = &Plus::plusd;
	Plus plus;
	cout << fc2(&plus, 1.1, 2.2) << endl;

	function<double(Plus, double, double)> fc3 = &Plus::plusd;
	cout << fc3(Plus(), 1.1, 2.2) << endl;

	return 0;
}

补充解释:隐藏的this指针变量实际上并不是确定的,传对象就是对象类型接收。

应用场景

逆波兰表达式

bind

std::bind 函数定义在头文件中, 是一个函数模板,它就像一个函数包装器 ( 适配器 ) 接受一个可 调用对象( callable object ),生成一个新的可调用对象来 适应 原对象的参数列表 。一般而言,我们用它可以把一个原本接收N 个参数的函数 fn ,通过绑定一些参数,返回一个接收 M 个( M 可以大于N ,但这么做没什么意义)参数的新函数。同时,使用 std::bind 函数还可以实现参数顺序调整等操作。

可以将 bind 函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对
象来 适应 原对象的参数列表。
调用 bind 的一般形式: auto newCallable = bind(callable,arg_list);
其中, newCallable 本身是一个可调用对象, arg_list 是一个逗号分隔的参数列表,对应给定的 callable的参数。 当我们调用 newCallable 时, newCallable 会调用 callable, 并传给它 arg_list 的参数
arg_list 中的参数可能包含形如 _n 的名字,其中 n 是一个整数,这些参数是 占位符 ,表newCallable的参数,它们占据了传递给 newCallable 的参数的 位置 。数值 n 表示生成的可调用对象中参数的位置:_1 newCallable 的第一个参数, _2 为第二个参数,以此类推。
#include <functional>
int Plus(int a, int b)
{
 return a + b;
}

class Sub
{
public:
	Sub(int x)
		:_x(x)
	{}

	int sub(int a, int b)
	{
		return (a - b)*_x;
	}

private:
	int _x;
};

int main()
{

// 绑定函数 
    auto f2 = bind(Sub, placeholders::_1, placeholders::_2);
	cout << f2(10, 5) << endl;
//function<int(int, int)> f1 = bind(Sub, placeholders::_1, placeholders::_2);

// 绑定成员函数
    auto f3 = bind(&Sub::sub, placeholders::_1, placeholders::_2, placeholders::_3);
//function<int(int, int)> 
    cout << f3(Sub(1), 10, 5) << endl;
    Sub sub(1);
	cout << f3(&sub, 10, 5) << endl;


// 绑定,调整参数个数,参数调换顺序
    auto f4 = bind(&Sub::sub, Sub(1), placeholders::_1, placeholders::_2);
	cout << f4(10, 5) << endl;

    auto f5 = bind(&Sub::sub, &sub, placeholders::_2, placeholders::_1);
	cout << f5(10, 5) << endl;

  return 0;
}

线程库

thread类的简单介绍

C++11 之前,涉及到多线程问题,都是和平台相关的,比如 windows linux 下各有自己的接
口,这使得代码的可移植性比较差 C++11 中最重要的特性就是对线程进行支持了,使得 C++
并行编程时不需要依赖第三方库 ,而且在原子操作中还引入了原子类的概念。要使用标准库中的
线程,必须包含 < thread > 头文件。

注意:
1. 线程是操作系统中的一个概念, 线程对象可以关联一个线程,用来控制线程以及获取线程的 状态
2. 当创建一个线程对象后,没有提供线程函数,该对象实际没有对应任何线程。
#include <thread>
int main()
{
 std::thread t1;
 cout << t1.get_id() << endl;
 return 0;
}
get_id() 的返回值类型为 id 类型, id 类型实际为 std::thread 命名空间下封装的一个类,该类中包含了一个结构体:
// vs下查看
typedef struct
{ /* thread identifier for Win32 */
 void *_Hnd; /* Win32 HANDLE */
 unsigned int _Id;
} _Thrd_imp_t;
3. 当创建一个线程对象后,并且给线程关联线程函数,该线程就被启动,与主线程一起运行。
线程函数一般情况下可按照以下三种方式提供:
  • 函数指针
  • lambda表达式
  • 函数对象
#include <iostream>
using namespace std;
#include <thread>
void ThreadFunc(int a)
{
 cout << "Thread1" << a << endl;
}
class TF
{
public:
 void operator()()
 {
 cout << "Thread3" << endl;
 }
};
int main()
{
    // 线程函数为函数指针
 thread t1(ThreadFunc, 10);
    
    // 线程函数为lambda表达式
 thread t2([]{cout << "Thread2" << endl; });
    
    // 线程函数为函数对象
    TF tf;
 thread t3(tf);
    
 t1.join();
 t2.join();
 t3.join();
 cout << "Main thread!" << endl;
 return 0;
}

4. thread 类是防拷贝的,不允许拷贝构造以及赋值,但是可以移动构造和移动赋值,即将一个
线程对象关联线程的状态转移给其他线程对象,转移期间不意向线程的执行。
5. 可以通过 joinable() 函数判断线程是否是有效的,如果是以下任意情况,则线程无效
  • 采用无参构造函数构造的线程对象
  • 线程对象的状态已经转移给其他线程对象
  • 线程已经调用join或者detach结束

线程函数参数

线程函数的参数是以值拷贝的方式拷贝到线程栈空间中的 ,因此:即使线程参数为引用类型,在
线程中修改后也不能修改外部实参,因为 其实际引用的是线程栈中的拷贝,而不是外部实参
#include <thread>
void ThreadFunc1(int& x)
{
 x += 10;
}
void ThreadFunc2(int* x)
{
 *x += 10;
}
int main()
{
 int a = 10;
 // 在线程函数中对a修改,不会影响外部实参,因为:线程函数参数虽然是引用方式,但其实际
//引用的是线程栈中的拷贝
 thread t1(ThreadFunc1, a);
 t1.join();
 cout << a << endl;
 // 如果想要通过形参改变外部实参时,必须借助std::ref()函数
 thread t2(ThreadFunc1, std::ref(a);
 t2.join();
 cout << a << endl;
 // 地址的拷贝
 thread t3(ThreadFunc2, &a);
 t3.join();
 cout << a << endl;
 return 0;
}
注意:如果是类成员函数作为线程参数时,必须将 this 作为线程函数参数。

用lambda可以不用ref()

void Print(int n, int& rx, mutex& rmtx)
{	
	rmtx.lock();

	for (int i = 0; i < n; i++)
	{
		// t1 t2
		++rx;
	}

	rmtx.unlock();
}

int main()
{
	int x = 0;
	mutex mtx;
	thread t1(Print, 1000000, ref(x), ref(mtx));
	thread t2(Print, 2000000, ref(x), ref(mtx));

	t1.join();
	t2.join();

	cout << x << endl;

	return 0;
}
int main()
{
	int x = 0;
	mutex mtx;

	auto func = [&](int n) {
		mtx.lock();
		for (size_t i = 0; i < n; i++)
		{
			++x;
		}
		mtx.unlock();
	};

	thread t1(func, 10000);
	thread t2(func, 20000);

	t1.join();
	t2.join();

	cout << x << endl;

	return 0;
}

原子性操作库(atomic)

多线程最主要的问题是共享数据带来的问题 ( 即线程安全 ) 。如果共享数据都是只读的,那么没问 题,因为只读操作不会影响到数据,更不会涉及对数据的修改,所以所有线程都会获得同样的数 据。但是,当一个或多个线程要修改共享数据时,就会产生很多潜在的麻烦
C++98 中传统的解决方式:可以对共享修改的数据可以加锁保护
#include <iostream>
using namespace std;
#include <thread>
#include <mutex>
std::mutex m;
unsigned long sum = 0L;
void fun(size_t num)
{
 for (size_t i = 0; i < num; ++i)
 {
 m.lock();
 sum++;
 m.unlock();
 }
}
int main()
{
 cout << "Before joining,sum = " << sum << std::endl;
 thread t1(fun, 10000000);
 thread t2(fun, 10000000);
 t1.join();
 t2.join();
 cout << "After joining,sum = " << sum << std::endl;
 return 0;
}
虽然加锁可以解决,但是加锁有一个缺陷就是:只要一个线程在对 sum++ 时,其他线程就会被阻
塞,会影响程序运行的效率,而且锁如果控制不好,还容易造成死锁。

注意:需要使用以上原子操作变量时,必须添加头文件
#include <iostream>
using namespace std;
#include <thread>
#include <atomic>
atomic_long sum{ 0 };
void fun(size_t num)
{
 for (size_t i = 0; i < num; ++i)
 sum ++;   // 原子操作
}
int main()
{
 cout << "Before joining, sum = " << sum << std::endl;
 thread t1(fun, 1000000);
 thread t2(fun, 1000000);
 t1.join();
 t2.join();
 
 cout << "After joining, sum = " << sum << std::endl;
 return 0;
}
C++11 中, 程序员不需要对原子类型变量进行加锁解锁操作,线程能够对原子类型变量互斥的
访问
更为普遍的,程序员可以 使用 atomic 类模板,定义出需要的任意原子类型

注意:原子类型通常属于 " 资源型 " 数据,多个线程只能访问单个原子类型的拷贝,因此 C++11
中,原子类型只能从其模板参数中进行构造,不允许原子类型进行拷贝构造、移动构造以及
operator= 等,为了防止意外,标准库已经将 atmoic 模板类中的拷贝构造、移动构造、赋值运算
符重载默认删除掉了。

#include <iostream>  
using namespace std;
#include <thread>
#include <mutex>
#include <atomic>

int main()
{
    
    vector<thread> vthd;
	int n;
	cin >> n;
	vthd.resize(n);
   atomic<int> x = 0;
   //atomic<int> x{ 0 };

    mutex mtx;
	auto func = [&](int n) {
		//mtx.lock();
		// 局部域
		{
			//LockGuard lock(mtx);

			//lock_guard<mutex> lock(mtx);
			for (size_t i = 0; i < n; i++)
			{
				++x;
			}
			//mtx.unlock();
		}

		/*for (size_t i = 0; i < n; i++)
		{
			cout << i << endl;
		}*/
	};

	for (auto& thd : vthd)
	{
		// 移动赋值
		thd = thread(func, 100000);
	}

	for (auto& thd : vthd)
	{
		thd.join();
	}
	cout << x << endl;
	printf("%d\n", x.load());
 
   return 0;
}

lock_guardunique_lock

在多线程环境下,如果想要保证某个变量的安全性,只要将其设置成对应的原子类型即可,即高 效又不容易出现死锁问题。但是有些情况下,我们可能需要保证一段代码的安全性,那么就只能 通过锁的方式来进行控制。
比如:一个线程对变量number 进行加一 100 次,另外一个减一 100 次,每次操作加一或者减一之 后,输出number 的结果,要求: number 最后的值为 1
#include <iostream>  
using namespace std;
#include <thread>
#include <mutex>
int number = 0;
mutex g_lock;
int ThreadProc1()
{
 for (int i = 0; i < 100; i++)
 {
 g_lock.lock();
 ++number;
 cout << "thread 1 :" << number << endl;
 g_lock.unlock();
 }
 return 0;
}
int ThreadProc2()
{
 for (int i = 0; i < 100; i++)
 {
 g_lock.lock();
 --number;
 cout << "thread 2 :" << number << endl;
 g_lock.unlock();
 }
 return 0;
}

int main()
{
 thread t1(ThreadProc1);
 thread t2(ThreadProc2);
 t1.join();
 t2.join();
 cout << "number:" << number << endl;
 system("pause");
 return 0;
}
上述代码的缺陷: 锁控制不好时,可能会造成死锁 ,最常见的 比如在锁中间代码返回,或者在锁
的范围内抛异常 。因此: C++11 采用 RAII 的方式对锁进行了封装,即 lock_guard unique_lock
class LockGuard
{
public:
	LockGuard(mutex& mtx)
		:_mtx(mtx)
	{
		_mtx.lock();
	}

	~LockGuard()
	{
		_mtx.unlock();
	}
private:
	mutex& _mtx;
};
#include <thread>
#include <mutex>
int main()
{
    
    vector<thread> vthd;
	int n;
	cin >> n;
	vthd.resize(n);
    int x = 0;


    mutex mtx;
	auto func = [&](int n) {
		//mtx.lock();
		// 局部域
		{
			//LockGuard lock(mtx);

			lock_guard<mutex> lock(mtx);
			for (size_t i = 0; i < n; i++)
			{
				++x;
			}
			//mtx.unlock();
		}

		/*for (size_t i = 0; i < n; i++)
		{
			cout << i << endl;
		}*/
	};

	for (auto& thd : vthd)
	{
		// 移动赋值
		thd = thread(func, 100000);
	}

	for (auto& thd : vthd)
	{
		thd.join();
	}
	cout << x << endl;
	printf("%d\n", x.load());
 
   return 0;
}

mutex的种类

C++11 中, Mutex 总共包了四个互斥量的种类:

1. std::mutex
C++11 提供的最基本的互斥量,该类的对象之间不能拷贝,也不能进行移动。 mutex 最常用
的三个函数:

注意,线程函数调用 lock() 时,可能会发生以下三种情况:
  • 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,
  • 该线程一直拥有该锁
  • 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住
  • 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)
线程函数调用 try_lock() 时,可能会发生以下三种情况:
  • 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock
  • 释放互斥量
  • 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉
  • 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)

2. std::recursive_mutex
允许同一个线程对互斥量多次上锁(即递归上锁),来获得对互斥量对象的多层所有权,
释放互斥量时需要调用与该锁层次深度相同次数的 unlock() ,除此之外,
std::recursive_mutex 的特性和 std::mutex 大致相同。

3. std::timed_mutex
std::mutex 多了两个成员函数, try_lock_for() try_lock_until()
  • ry_lock_for()
接受一个时间范围,表示在这一段时间范围之内线程如果没有获得锁则被阻塞住(与
std::mutex try_lock() 不同, try_lock 如果被调用时没有获得锁则直接返回
false ),如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超
时(即在指定时间内还是没有获得锁),则返回 false
  • try_lock_until()
接受一个时间点作为参数,在指定时间点未到来之前线程如果没有获得锁则被阻塞住,
如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超时(即在指
定时间内还是没有获得锁),则返回 false

4. std::recursive_timed_mutex

lock_guard
template<class _Mutex>
class lock_guard
{
public:
// 在构造lock_gard时,_Mtx还没有被上锁
 explicit lock_guard(_Mutex& _Mtx)
 : _MyMutex(_Mtx)
 {
 _MyMutex.lock();
 }
// 在构造lock_gard时,_Mtx已经被上锁,此处不需要再上锁
lock_guard(_Mutex& _Mtx, adopt_lock_t)
 : _MyMutex(_Mtx)
 {}
 ~lock_guard() _NOEXCEPT
 {
 _MyMutex.unlock();
 }
 lock_guard(const lock_guard&) = delete;
 lock_guard& operator=(const lock_guard&) = delete;
private:
 _Mutex& _MyMutex;
};
通过上述代码可以看到, lock_guard 类模板主要是通过 RAII 的方式,对其管理的互斥量进行了封
,在需要加锁的地方,只需要用上述介绍的 任意互斥体实例化一个 lock_guard ,调用构造函数
成功上锁,出作用域前, lock_guard 对象要被销毁,调用析构函数自动解锁,可以有效避免死锁
问题
lock_guard 的缺陷:太单一,用户没有办法对该锁进行控制 ,因此 C++11 又提供了
unique_lock

unique_lock
lock_gard 类似, unique_lock 类模板也是采用 RAII 的方式对锁进行了封装,并且也是以独占所
有权的方式管理 mutex 对象的上锁和解锁操作,即其对象之间不能发生拷贝 。在构造 ( 或移动
(move) 赋值 ) 时, unique_lock 对象需要传递一个 Mutex 对象作为它的参数,新创建的unique_lock 对象负责传入的 Mutex 对象的上锁和解锁操作。 使用以上类型互斥量实例化 unique_lock 的对象时,自动调用构造函数上锁, unique_lock 对象销毁时自动调用析构函数解 锁,可以很方便的防止死锁问题

与lock_guard不同的是,unique_lock更加的灵活,提供了更多的成员函数:

  • 上锁/解锁操作locktry_locktry_lock_fortry_lock_untilunlock
  • 修改操作:移动赋值、交换(swap:与另一个unique_lock对象互换所管理的互斥量所有权)、释放(release:返回它所管理的互斥量对象的指针,并释放所有权)
  • 获取属性owns_lock(返回当前对象是否上了锁)operator bool()(owns_lock()的功能相同)mutex(返回当前unique_lock所管理的互斥量的指针)

条件变量

支持两个线程交替打印,一个打印奇数,一个打印偶数
#include <iostream>
using namespace std;  
#include <thread>
#include <mutex>
#include <condition_variable>

int main()
{
	std::mutex mtx;
	condition_variable c;
	int n = 100;
	bool flag = true;

	thread t2([&]() {
		int j = 1;
		while (j < n)
		{
			unique_lock<mutex> lock(mtx);

			// 只要flag == true t2一直阻塞'
			// 只要flag == false t2不会阻塞
			while (flag)
				c.wait(lock);

			cout << j << endl;
			j += 2; // 奇数
			flag = true;

			c.notify_one();
		}
		});


	this_thread::sleep_for(std::chrono::milliseconds(1000));


	// 第一个打印的是t1打印0
	thread t1([&]() {
		int i = 0;
		while (i < n)
		{
			unique_lock<mutex> lock(mtx);
			// flag == false t1一直阻塞
			// flag == true t1不会阻塞
			while (!flag)
			{
				c.wait(lock);
			}

			cout << i << endl;

			flag = false;
			i += 2; // 偶数

			c.notify_one();
		}
	});


	t1.join();
	t2.join();

	return 0;
}

其他例子:

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id(int id) {
	std::unique_lock<std::mutex> lck(mtx);
	while (!ready) 
		cv.wait(lck);

	std::cout << "thread " << id << '\n';
}

void go() {
	std::unique_lock<std::mutex> lck(mtx);
	ready = true;
	cv.notify_all();
}

int main()
{
	std::thread threads[10];

	// spawn 10 threads:
	for (int i = 0; i < 10; ++i)
		threads[i] = std::thread(print_id, i);

	std::cout << "10 threads ready to race...\n";

	this_thread::sleep_for(std::chrono::milliseconds(100));

	go();                       // go!

	for (auto& th : threads)
		th.join();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

你好,赵志伟

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值