C++ 11

文章目录

  • [1. 统一的列表初始化](#1. 统一的列表初始化)
    • [1.1 {}初始化](#1.1 {}初始化)
    • [1.2 std::initializer_list](#1.2 std::initializer_list)
  • [2. 声明](#2. 声明)
    • [2.1 auto](#2.1 auto)
    • [2.2 decltype](#2.2 decltype)
    • [2.3 nullptr](#2.3 nullptr)
  • [3. 右值引用和移动语义](#3. 右值引用和移动语义)
    • [3.1 左值引用和右值引用](#3.1 左值引用和右值引用)
    • [3.2 左值引用和右值引用的比较](#3.2 左值引用和右值引用的比较)
    • [3.3 其它使用场景分析](#3.3 其它使用场景分析)
    • [3.4 完美转发](#3.4 完美转发)
  • [4. 新的类的功能](#4. 新的类的功能)
    • [4.1 默认成员函数](#4.1 默认成员函数)
    • [4.2 强制编译器生成默认函数的关键字default](#4.2 强制编译器生成默认函数的关键字default)
    • [4.3 禁止生成默认函数的关键字delete](#4.3 禁止生成默认函数的关键字delete)
    • [4.4 final和override](#4.4 final和override)
  • [5. 可变参数模板](#5. 可变参数模板)
    • [5.1 基础使用](#5.1 基础使用)
    • [5.2 STL容器中的empalce相关接口函数:](#5.2 STL容器中的empalce相关接口函数:)
  • [6. lambda 表达式](#6. lambda 表达式)
    • [6.1 引入](#6.1 引入)
    • [6.2 lambda表达式语法](#6.2 lambda表达式语法)
    • [6.3 捕获列表](#6.3 捕获列表)
    • [6.4 函数对象与lambda表达式](#6.4 函数对象与lambda表达式)
  • [7. 包装器](#7. 包装器)
    • [7.1 基础使用](#7.1 基础使用)
    • [7.2 一个题目](#7.2 一个题目)
    • [7.3 包装器包装成员函数](#7.3 包装器包装成员函数)
    • [7.4 std::bind()](#7.4 std::bind())

1. 统一的列表初始化

1.1 {}初始化

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

cpp 复制代码
void test1()
{
	struct Point
	{
		int _x;
		int _y; 
	};
	int array1[] = { 1, 2, 3, 4, 5 };
	int array2[5] = { 0 };
	Point p = { 1, 2 };
}

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

cpp 复制代码
void test2()
{
	struct Point
	{
		int _x;
		int _y;
	};
	int x1{ 1 };
	int array1[]{ 1, 2, 3, 4, 5 };
	int array2[5]{ 0 };
	Point p{ 1, 2 };
	// C++11中列表初始化也可以适用于new表达式中,此时数组为0,0,0,0
	int* pa = new int[4] { 0 };
	int* pb = new int[4] {1, 2, 3, 4};	// 此时数组为1,2,3,4
}

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

cpp 复制代码
void test3()
{
	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;
	};
	Date d1(2024, 9, 15);
	// c++11支持的列表初始化
	Date d2 = { 2024, 9, 15 };
	Date d3{ 2024,9,15 };
    // C++11中列表初始化也可以适用于new表达式中
	Date* d4 = new Date{ 2024, 2,13 };
    Date* d5 = new Date[4]{ d1, d2, {2024, 9,16}, {2024,9,17} };
}

20,21行实际上是先构造了一个临时对象,再拷贝临时对象,验证:

cpp 复制代码
// 因为临时对象具有常性
Date& d2 = { 2024, 9, 15 };			 // err
const Date& d2 = { 2024, 9, 15 };	 // ok

所以第18行:直接调用构造函数

第20,21行:构造+拷贝构造 ==》编译器优化为直接调用构造

1.2 std::initializer_list

官方文档

下面这种类型会被自动识别为initializer_list

cpp 复制代码
void test4()
{
	auto il = { 1, 2,3,4 };
	cout << typeid(il).name() << endl;
}

initializer_list是一个类,本质上是用了一个_first指针和一个_last指针,指向可迭代的对象的开始和结束位置的下一个,接着封装迭代器。所以可以使用迭代器遍历,也可以实现范围for

cpp 复制代码
void test4()
{
	initializer_list<int> il = { 1, 2, 3, 4, 5 };
	cout << typeid(il).name() << endl;
	initializer_list<int>::iterator it = il.begin();
	while (it != il.end()) {
		cout << *it << ' ';
		it++;
	}
	cout << endl;
	for (const auto& e : il) {
		cout << e << ' ';
	}
}

使用场景:

std::initializer_list一般是作为构造函数的参数,C++11对STL中的不少容器就增加std::initializer_list作为参数的构造函数,这样初始化容器对象就更方便了。也可以作为operator=的参数,这样就可以用大括号赋值。

cpp 复制代码
void test5()
{
	vector<int> v = { 1,2,3,4 };
	list<int> l = { 5,6,7,8 };
	// 这里{"sort", "排序"} 会先初始化构造一个pair对象,接着再使用initializer_list  
	map<string, string> m = { {"sort", "排序"}, {"apple", "苹果"} };
	// 使用operator()对容器赋值
	v = { 3,4,5,6 };
}

让模拟实现的vector也支持{}初始化和赋值

cpp 复制代码
template<class T>
class vector
{
    // ...
    vector(initializer_list<value_type> lt)
    {
        reserve(lt.size());
        for (const auto& e : lt)	push_back(e);
    }
    
    vector<value_type>& operator=(initializer_list<value_type> v)
    {
        swap(v);
        return *this;
    }
    // ...
}

2. 声明

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

2.1 auto

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

2.2 decltype

关键字decltype将变量的类型声明为表达式指定的类型

cpp 复制代码
void test6()
{
	
	int x = 1;
	double y = 1.2;
	cout << typeid(decltype(x * y)).name() << endl;
	vector<decltype(x* y)> v;
	v.push_back(1.2);
	v.push_back(2.1);
	v.push_back(3.1);
	for (const auto& e : v) cout << e << ' ';
}

2.3 nullptr

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

cpp 复制代码
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif

3. 右值引用和移动语义

3.1 左值引用和右值引用

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

什么是左值?什么是左值引用?

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

cpp 复制代码
// 以下的p、b、c、*p都是左值
int* p = new int(0);
int b = 1;
const int c = 2;
// 以下几个是对上面左值的左值引用
int*& rp = p;
int& rb = b;
const int& rc = c;
int& pvalue = *p;

什么是右值?什么是右值引用?

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

cpp 复制代码
double x = 1.1, y = 2.2;
// 以下几个都是常见的右值
10;
x + y;
fmin(x, y);

// 以下几个都是对右值的右值引用
int&& rr1 = 10;
double&& rr2 = x + y;
double&& rr3 = fmin(x, y);

// 这里编译会报错:error C2106: "=": 左操作数必须为左值
10 = 1;
x + y = 1;
fmin(x, y) = 1;		

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

cpp 复制代码
double x = 1.1, y = 2.2;
int&& rr1 = 10;
const double&& rr2 = x + y;
rr1 = 20;
rr2 = 5.5; // 报错

3.2 左值引用和右值引用的比较

左值引用总结

  1. 左值引用只能引用左值,不能引用右值。
  2. 但是const左值引用既可引用左值,也可引用右值
cpp 复制代码
// 左值引用只能引用左值,不能引用右值。
int a = 10;
int& ra1 = a; // ra为a的别名
//int& ra2 = 10; // 编译失败,因为10是右值
// const左值引用既可引用左值,也可引用右值。
const int& ra3 = 10;
const int& ra4 = a;

右值引用总结

  1. 右值引用只能右值,不能引用左值。
  2. 但是右值引用可以用move以后的左值。
cpp 复制代码
// 右值引用只能右值,不能引用左值。
int&& r1 = 10;

int a = 10;
int&& r2 = a;		/*error C2440: "初始化": 无法从"int"转换为"int &&", message : 无法将左值绑定到右值引用*/

// 右值引用可以引用move以后的左值
int&& r3 = move(a);

左值引用的短板:

当函数返回对象是一个局部变量,出了函数作用域就不存在了,就不能使用左值引用返回,只能传值返回。例如:lyf::string to_string(int value)函数中可以看到,这里只能使用传值返回,传值返回会导致至少1次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)。

cpp 复制代码
namespace lyf
{
	class string
	{
	public:
		typedef char* iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		explicit 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& s)
		{
			::swap(_str, s._str);
			::swap(_size, s._size);
			::swap(_capacity, s._capacity);
		}
		// 拷贝构造
		string(const string& s)
			:_str(nullptr)
		{
			cout << "string(const string& s) -- 深拷贝" << endl;
			string tmp(s._str);
			swap(tmp);
		}
		// 赋值重载
		string& operator=(const string& s)
		{
			cout << "string& operator=(string s) -- 深拷贝" << endl;
			/*string tmp(s);
			swap(tmp);*/
			if (this != &s) {
				char* tmp = new char[s._capacity + 1];
				strcpy(tmp, _str);
				delete _str;
				_str = tmp;
				_capacity = s._capacity + 1;
				_size = s._size;

			}
			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;
		size_t _size;
		size_t _capacity; // 不包含最后做标识的\0
	};

	// 将某一个正数转为string
	string to_string(int val)
	{
		string ret;
		do
		{
			ret += (val % 10 + '0');
			val /= 10;
		} while (val);
		reverse(ret.begin(), ret.end());
		return ret;
	}

	void test_string1()
	{
		string s;
		s = to_string(123);
	}
}
int main()
{
	lyf::test_string1();
	return 0;
}

实际上,c++11将在to_sting()中的ret规定为右值,右值有两种分类,一是自定义类型,而是像ret这样自定义类型的将亡值

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

cpp 复制代码
// 移动构造
string(string&& s)
    :_str(nullptr)
{
    cout << "string(string&& s) -- 移动构造" << endl;
    swap(s);
}

lyf::string中增添移动构造,移动构造的本质是将参数右值的资源转移过来,占为己有,这样就不用做深拷贝了,所以它叫移动构造,就是转移别人的资源来构造自己。

这时我们发现没有调用深拷贝的拷贝构造,而是调用了移动构造,移动构造中没有新开空间,拷贝数据,而是转移数据,所以效率更高了

不仅有移动构造,还有移动赋值

lyf::string中增添移动赋值,这次是将s = to_string(123);返回的将亡右值转移给s对象,此时调用的是移动赋值

cpp 复制代码
// 移动赋值
string& operator=(string&& s)
{
    cout << "string& operator=(string&& s) -- 移动赋值" << endl;
    swap(s);
    return *this;
}

看看地址

这里运行后,我们看到调用了一次移动构造和一次移动赋值。因为如果是用一个已经存在的对象接收,编译器就没办法优化了。bit::to_string函数中会先用str生成构造生成一个临时对象,但是我们可以看到,编译器很聪明的在这里把str识别成了右值,调用了移动构造。然后在把这个临时对象做为bit::to_string函数调用的返回值赋值给ret1,这里调用的移动赋值。

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

cpp 复制代码
vector (vector&& x);
vector (vector&& x, const allocator_type& alloc);

list (list&& x);
list (list&& x, const allocator_type& alloc);

一个小问题

cpp 复制代码
 void test_string2()
 {
     string s1("hello world");
     string s2(s1);
     string s3 = move(s1);
 }

这里如果将move(s1)后,编译器会把它识别成右值,调用移动构造,当构造玩s3后,s1会被清空,所以不要轻易把一个左值给move()

cpp 复制代码
string s1("hello world");
move(s1);
// 注意,move并没有改变s1的属性,下面调用的还是拷贝构造
string s2 = s1;

3.3 其它使用场景分析

c++11 不仅增加了移动构造和移动赋值,插入函数也增加了右值版本

cpp 复制代码
// std::list::push_back
void push_back (const value_type& val);
void push_back (value_type&& val);

// std::set::insert
pair<iterator,bool> insert (const value_type& val);
pair<iterator,bool> insert (value_type&& val);

std::list和我们上面自己写的string举例:

cpp 复制代码
list<lyf::string> lt;
lyf::string s("aaaaaaaaa");
// 左值
lt.push_back(s);
// 右值
lt.push_back(lyf::to_string(123));

自己实现一下list的右值push_back()版本

cpp 复制代码
// list.hpp
namespace lyf
{
	// 节点
	template <class T>
	struct list_node
	{
		list_node* _next;
		list_node* _prev;
		T _data;
		list_node(const T& x = T())
			:_next(nullptr)
			,_prev(nullptr)
			,_data(x)
		{}
	};

	// 迭代器
	template <class T, class Ref, class Ptr>	
	struct __list_iterator
	{
		typedef list_node<T> node;
		typedef __list_iterator<T, Ref, Ptr> self;
		node* _node;
		
		// 构造函数
		__list_iterator(node* x) 
			:_node(x){}
		Ref& operator*()
		{
			// 重载解引用运算符
			return _node->_data;
		}
		Ptr operator->()
		{
			return &(_node->_data);
		}
		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& s)
		{
			return _node != s._node;
		}
		bool operator==(const self& s)
		{
			return _node == s._node;
		}
	};

	// 链表
	template<class T>
	class list
	{
	public:
		typedef list_node<T> node;
		typedef __list_iterator<T, T&, T*> iterator;
		typedef __list_iterator<T, const T&, const T*> const_iterator;
	public:
		list()
		{
			_head = new node;
			_head->_next = _head;
			_head->_prev = _head;
		}
		iterator begin() { return iterator(_head->_next); }
		iterator end() { return iterator(_head); }	 // end是_head;
		iterator begin() const { return iterator(_head->_next); }
		iterator end() const { return iterator(_head); }

		void push_back(const T& x)
		{
			insert(end(), x);
		}
		// 右值引用版本
		void push_back(T&& x)
		{
			insert(end(), x);
		}
		void insert(iterator pos, const T& x)
		{
			node* newNode = new node(x);
			node* cur = pos._node;	// 这里要获得pos的_node
			node* prev = cur->_prev;

			prev->_next = newNode;
			newNode->_prev = prev;
			newNode->_next = cur;
			cur->_prev = newNode;
		}
		// insert的右值引用版本
		void insert(iterator pos, T&& x)
		{
			node* newNode = new node(x);
			node* cur = pos._node;	// 这里要获得pos的_node
			node* prev = cur->_prev;

			prev->_next = newNode;
			newNode->_prev = prev;
			newNode->_next = cur;
			cur->_prev = newNode;
		}

		void push_front(const T& x) { insert(begin(), x); }
		void erase(iterator pos)
		{
			assert(pos != end());
			// erase会导致迭代器失效,因为pos位置的节点已经被删除了
			node* prev = pos._node->_prev;
			node* next = pos._node->_next;
			prev->_next = next;
			next->_prev = prev;
			delete pos._node;	// 没有中括号
		}
		void pop_back()
		{
			erase(--end());
		}
		void pop_front()
		{
			erase(begin());
		}
	private:
		node* _head;
	};
}
cpp 复制代码
#include "list.hpp"

void TestMyList()
{
	lyf::list<lyf::string> lt;
	lyf::string s("aaaaaaaaa");
	// 左值
	lt.push_back(s);
	// 右值
	lt.push_back("11111");		// 1111是一个临时对象,编译器把它识别成右值
}
int main()
{
	TestMyList();
    return 0;
}

可以看到,这样写并不对(注意,这里的第一个深拷贝是因为我们在list()的构造函数里面new了一个node

调试看一下原因

可以看到,第二次调用insert()走的是左值引用版本

实际上:一个右值被右值引用以后的属性是左值 ,这是编译器规定的,因为右值被右值引用需要被修改(说明该属性是左值),如果不能修改的话,前面的移动构造和移动赋值就没法swap()了。

一种解决方案:move()一下x

3.4 完美转发

模板中的万能引用 ,只有函数模板有这样的用法

cpp 复制代码
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);
}

void test10()
{
	PerfectForward(10); // 右值
	int a;
	PerfectForward(a); // 左值
	PerfectForward(move(a)); // 右值
	const int b = 8;
	PerfectForward(b); // const 左值
	PerfectForward(move(b)); // const 右值
}

**std::forward 完美转发在传参的过程中保留对象原生类型属性 **

cpp 复制代码
// std::forward<T>(t)在传参的过程中保持了t的原生类型属性
template<typename T>
void PerfectForward(T&& t)
{
	Fun(forward<T>(t));
}

所以3.3的另一种解决方案是使用完美转发

4. 新的类的功能

4.1 默认成员函数

原来C++类中,有6个默认成员函数:

  1. 构造函数
  2. 析构函数
  3. 拷贝构造函数
  4. 拷贝赋值重载
  5. 取地址重载
  6. const 取地址重载

最后重要的是前4个,后两个用处不大。默认成员函数就是我们不写编译器会生成一个默认的。C++11 新增了两个:移动构造函数和移动赋值运算符重载

  • 如果你没有自己实现移动构造函数,且没有实现析构函数 、拷贝构造、拷贝赋值重载中的任意一个 (即都没有实现)。那么编译器会自动生成一个默认移动构造。默认生成的移动构造函数,对于内置类型成员会执行逐成员按字节拷贝,自定义类型成员,则需要看这个成员是否实现移动构造,如果实现了就调用移动构造,没有实现就调用拷贝构造
  • 如果你没有自己实现移动赋值重载函数,且没有实现析构函数 、拷贝构造、拷贝赋值重载中的任意一个,那么编译器会自动生成一个默认移动赋值。默认生成的移动构造函数,对于内置类型成员会执行逐成员按字节拷贝,自定义类型成员,则需要看这个成员是否实现移动赋值,如果实现了就调用移动赋值,没有实现就调用拷贝赋值。(默认移动赋值跟上面移动构造完全类似)
  • 如果你提供了移动构造或者移动赋值,编译器不会自动提供拷贝构造和拷贝赋值。
cpp 复制代码
class Person
{
public:
    Person(const char* name = "", int age = 0)
        :_name(name)
        , _age(age)
    {}
    /*Person(const Person& p)
        :_name(p._name)
        ,_age(p._age)
    {}*/
    /*Person& operator=(const Person& p)
    {
        if(this != &p) {
            _name = p._name;
            _age = p._age;
        }
        return *this;
    }*/
    /*~Person()
    {}*/
private:
    lyf::string _name;
    int _age;
};

void test11()
{
    Person s1("aaa", 123);
    Person s2 = s1;
    Person s3 = move(s1);
    Person s4;
    s4 = move(s2);
}

4.2 强制编译器生成默认函数的关键字default

C++11可以让你更好的控制要使用的默认函数。假设你要使用某个默认的函数,但是因为一些原因这个函数没有默认生成。比如:我们提供了拷贝构造,就不会生成移动构造了,那么我们可以使用default关键字显示指定移动构造生成。

cpp 复制代码
class Person
{
public:
    Person(const char* name = "", int age = 0)
        :_name(name)
        , _age(age)
    {}
    Person(const Person& p)
        :_name(p._name)
        ,_age(p._age)
    {}
    Person& operator=(const Person& p)
    {
        if(this != &p) {
            _name = p._name;
            _age = p._age;
        }
        return *this;
    }
    ~Person()
    {}
    // 强制编译器使用默认函数
    Person(Person&& p) = default;
    Person& operator=(Person&& p) = default;
private:
    lyf::string _name;
    int _age;
};

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

如果能想要限制某些默认函数的生成,在C++98中,是该函数设置成private,并且只声明不定义,这样只要其他人想要调用就会报错。在C++11中更简单,只需在该函数声明加上=delete即可,该语法指示编译器不生成对应函数的默认版本,称=delete修饰的函数为删除函数

cpp 复制代码
Person(Person&& p) = delete;
// ...
Person s3 = move(s1);	// error C2280: "Person::Person(Person &&)": 尝试引用已删除的函数

4.4 final和override

  1. final:修饰虚函数,表示该虚函数不能再被重写

    cpp 复制代码
    class A
    {
    public:
    	virtual void func() final{
    		cout << "A func()" << endl;
    	}
    };
    class B : public A
    {
    public:
    	// 父类的func()加上final后就不能不重写了
    	virtual void func() {		// error C3248: "A::func": 声明为 "final" 的函数不能由 "B::func" 重写
    		cout << "B func()" << endl;
    	}
    };
  2. override: 检查派生类虚函数是否重写了基类某个虚函数,如果没有重写编译报错

    cpp 复制代码
    class A
    {
    public:
    	virtual void func(){
    		cout << "A func()" << endl;
    	}
    };
    class B : public A
    {
    public:
    	// 加上override之后,子类如果没完成重写就会编译错误
    	virtual void func() override {
    		cout << "B func()" << endl;
    	}
    };

5. 可变参数模板

5.1 基础使用

下面就是一个基本可变参数的函数模板

cpp 复制代码
// Args是一个模板参数包,args是一个函数形参参数包
// 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。
template <class ...Args>
void ShowList(Args... args)
{
    // 计算有几个参数
    cout << sizeof...(args) << endl;
}

void test12()
{
    ShowList(1);
    ShowList(1, 2);
    ShowList(1, 2, 3.3);
    ShowList(1, 2, 3.3, "string");
}

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

模版参数包的解析

cpp 复制代码
// 递归终止函数
template <class T>
void ShowList(const T& t)
{
    cout << t << endl;
}
// 编译时的递归推演,第一个模版参数依次解析获取参数值
template <class T, class ...Args>
void ShowList(T value, Args... args)
{
    cout << value << " ";
    ShowList(args...);
}

void test12()
{
    ShowList(1);
    ShowList(1, 2);
    ShowList(1, 2, 3.3);
    ShowList(1, 2, 3.3, "string");
}

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

vector的emplace_back() list的emplace_back()

cpp 复制代码
template <class... Args>
void emplace_back (Args&&... args);

可以看到的emplace系列的接口,支持模板的可变参数,并且万能引用。那么相对push和emplace系列接口的优势到底在哪里呢?

cpp 复制代码
void test13()
{
    // 这样没什么区别
    std::list<lyf::string> lt;
    lyf::string s1("aaa");
    lt.push_back(s1);
    lt.push_back(move(s1));
    cout << "===================" << endl;
    lyf::string s2("bbb");
    lt.emplace_back(s2);
    lt.emplace_back(move(s2));
}
cpp 复制代码
void test14()
{
    std::list<lyf::string> lt;
    lt.push_back("aaaa");
    cout << "===================" << endl;
    lt.emplace_back("bbbb");
}

lyf::string构造函数的打印放出来,方便观察

由于是可变模版参数,所以如果是pair的话可以这样写,多参数的时候可以一个一个参数传递,因为emplace_back()的形参是可变参数包,可以直接把参数包不断往下传递,直到构建到节点val上。

cpp 复制代码
void test15()
{
    std::list<pair<int, lyf::string>> lt;
    lt.push_back({ 1, "aa" });
    cout << "===================" << endl;
    lt.emplace_back(2, "bb");
}

可以看到,emplace()版本略微高效,并没有很大的提升,因为移动构造的成本也是足够低的(对于深拷贝的类来说),但是一个浅拷贝的类,而且非常大,此时empace()还是很有效果的,毕竟省了移动构造。

6. lambda 表达式

6.1 引入

C++98中,如果想要对一个数据集合中的元素进行排序,可以使用std::sort方法,如果待排序元素为自定义类型,需要用户定义排序时的比较规则:

cpp 复制代码
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;
    }
};

void test16()
{
    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表达式

6.2 lambda表达式语法

lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement }

  • [capture-list] : 捕捉列表 ,该列表总是出现在lambda函数的开始位置,编译器根据[]来判断接下来的代码是否为lambda函数,捕捉列表能够捕捉上下文中的变量供lambda函数使用。
  • (parameters):参数列表与普通函数的参数列表一致,如果不需要参数传递,则可以连同()一起省略
  • mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量性。使用该修饰符时,参数列表不可省略(即使参数为空)。
  • ->returntype:返回值类型 。用追踪返回类型形式声明函数的返回值类型,没有返回值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推导。
  • {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获到的变量。
cpp 复制代码
sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2)->bool {
    return g1._evaluate < g2._evaluate;
});

auto f1 = [](int x) {cout << x << endl; };
f1(1);

lambda表达式实际上可以理解为匿名函数对象 ,重载了operator(),就是个仿函数。无法直接调用,如果想要直接调用,可借助auto将其赋值给一个变量

cpp 复制代码
void test17()
{
    auto f1 = [](int x) {cout << x << endl; };
    cout << typeid(f1).name() << endl;		// class `void __cdecl test17(void)'::`2'::<lambda_1>
}

6.3 捕获列表

捕获列表说明捕捉列表描述了上下文中那些数据可以被lambda使用,以及使用的方式传值还是传引用捕捉过来后,就会变成该类的成员变量

  • [var]:表示值传递方式捕捉变量var,即将捕捉到的作为lambda类中的const 成员变量
  • [=]:表示值传递方式捕获所有父作用域中的变量(包括this)
  • [&var]:表示引用传递捕捉变量var ,将lambda类中成员变量引用到外面的值
  • [&]:表示引用传递捕捉所有父作用域中的变量(包括this)
  • [this]:表示值传递方式捕捉当前的this指针

注意

  • **父作用域指包含lambda函数的语句块 **
  • 语法上捕捉列表可由多个捕捉项组成,并以逗号分割比如:[=, &a, &b]:以引用传递的方式捕捉变量a和b,值传递方式捕捉其他所有变量[&,a, this]:值传递方式捕捉变量a和this,引用方式捕捉其他变量
  • 捕捉列表不允许变量重复传递,否则就会导致编译错误比如:[=, a]:=已经以值传递方式捕捉了所有变量,捕捉a重复
  • 在块作用域以外的lambda函数捕捉列表必须为空
  • 在块作用域中的lambda函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域或者非局部变量都会导致编译报错。
cpp 复制代码
int x = 1, y = 2;
auto f1 = [](int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
    cout << x << ' ' << y << endl;
};
f1(x, y);
cout << x << ' ' << y << endl;
cout << "============================================" << endl;
// 使用捕获列表,需要加mutable,并不会修改外面的值,因为是值传递方式
auto f2 = [x, y]() mutable {
    int temp = x;
    x = y;
    y = temp;
    cout << x << ' ' << y << endl;
};
f2();
cout << x << ' ' << y << endl;
cout << "============================================" << endl;
// 使用传引用
auto f3 = [&x, &y]() {
    int temp = x;
    x = y;
    y = temp;
    cout << x << ' ' << y << endl;
};
f2();
cout << x << ' ' << y << endl;

6.4 函数对象与lambda表达式

函数对象,又称为仿函数,即可以想函数一样使用的对象,就是在类中重载了operator()运算符的类对象。

如6.1中ComparePriceLess定义出来的对象就是

从使用方式上来看,函数对象与lambda表达式完全一样。函数对象将rate作为其成员变量,在定义对象时给出初始值即可,lambda表达式通过捕获列表可以直接将该变量捕获到。

实际在底层编译器对于lambda表达式的处理方式,完全就是按照函数对象的方式处理的,即:如果定义了一个lambda表达式,编译器会自动生成一个类,在该类中重载了operator()。

7. 包装器

现在一共有3个可调用对象

  • 函数指针
  • 仿函数
  • lambda

可以用包装器包装这三种类型

7.1 基础使用

cpp 复制代码
std::function在头文件<functional>
// 类模板原型如下
template <class T> function; // undefined
template <class Ret, class... Args>
class function<Ret(Args...)>;
模板参数说明:
Ret: 被调用函数的返回类型
Args...:被调用函数的形参
cpp 复制代码
void Swap1(int& x, int& y)
{
    int temp = x;
    x = y;
    y = temp;
}

struct Swap2
{
    void operator()(int& x, int& y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
};

void test19()
{
    int x = 1, y = 2;
    // 使用包装器包装
    map <string, function<void(int&, int&)>> cmdOp;
    cmdOp.insert({ "函数指针", Swap1 });
    cmdOp.insert({ "仿函数", Swap2()});
    cmdOp.insert({ "lambda", [](int& x, int& y) {
        int temp = x;
        x = y;
        y = temp;
} });
    cmdOp["函数指针"](x, y);
    cout << x << ' ' << y << endl;
    cmdOp["仿函数"](x, y);
    cout << x << ' ' << y << endl;
    cmdOp["lambda"](x, y);
    cout << x << ' ' << y << endl;
    //也可以这样写
    function<void(int&, int&)> f1 = Swap1;
    f1(x, y);
    cout << x << ' ' << y << endl;
    function<void(int&, int&)> f2 = Swap2();
    f2(x, y);
    cout << x << ' ' << y << endl;
}

7.2 一个题目

这个题可以用包装器做

之前用栈的解法

cpp 复制代码
// 遇到操作符就出栈运算(注意顺序),数字就入栈
class Solution {
    stack<int> st;
public:
    int evalRPN(vector<string>& tokens) {
        for (auto& str : tokens) {
            if (str == "+" || str == "-" || str == "*" || str == "/") {
                int r = st.top();
                st.pop();
                int l = st.top();
                st.pop();
                switch (str[0]) {
                case '+':
                    st.push(l + r);
                    break;
                case '-':
                    st.push(l - r);
                    break;
                case '*':
                    st.push(l * r);
                    break;
                case '/':
                    st.push(l / r);
                    break;
                }
            } else
                st.push(stoi(str));
        }
        return st.top();
    }
};

包装器的解法,简化了代码

cpp 复制代码
class Solution {
    stack<int> st;
public:
    int evalRPN(vector<string>& tokens) {
        unordered_map<string, function<int(int, int)>> cmdOp = {
            {"+", [](int x, int y) { return x + y; }},
            {"-", [](int x, int y) { return x - y; }},
            {"*", [](int x, int y) { return x * y; }},
            {"/", [](int x, int y) { return x / y; }},
        };
        for (auto& str : tokens) {
            if (cmdOp.count(str)) {
                int r = st.top();
                st.pop();
                int l = st.top();
                st.pop();
                st.push(cmdOp[str](l, r));
            } else
                st.push(stoi(str));
        }
        return st.top();
    }
};

7.3 包装器包装成员函数

cpp 复制代码
class Plus
{
public:
    static int PlusI(int x, int y)
    {
        return x + y;
    }

    double PlusD(double x, double y) 
    {
        return x + y;
    }
};

void test20()
{
    // 成员函数包装的时候,需要加类域和&(静态可以不加&)
    function<int(int, int)> f1 = Plus::PlusI;
    cout << f1(1, 2) << endl;
    // 有this指针
    function<double(Plus*, double, double)> f2 = &Plus::PlusD;      // 底层是用这个指针调用PlusD函数
    Plus ps;
    cout << f2(&ps, 1.1, 2.2) << endl;
    // cout << f2(&Plus(), 1.1, 2.2) << endl;    // 这是错误的,因为Plus()返回的是一个右值,右值不能取地址
    // 也可以这样写
    function<double(Plus, double, double)> f3 = &Plus::PlusD;
    cout << f3(Plus(), 1.1, 2.2) << endl;       // 底层用这个对象调用PlusD函数
}

Plus*Plus()比较烦,所以就引入了std::bind()

7.4 std::bind()

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

cpp 复制代码
// 原型如下:
template <class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);
// with return type (2)
template <class Ret, class Fn, class... Args>
/* unspecified */ bind (Fn&& fn, Args&&... args);

可以将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为第二个参数,以此类推

cpp 复制代码
int Sub(int x, int y)
{
    return x - y;
}

void test21()
{
    function<int(int,int)> f = Sub;
    cout << f(1, 2) << endl;    // 1 - 2
    // 调整参数的位置,将传递的第一个参数作为Sub函数的y,第二个参数作为Sub函数的x,这里可以用auto接收,也可以用包装器
    auto f2 = bind(Sub, placeholders::_2, placeholders::_1);
    cout << f2(1, 2) << endl;       // 2 - 1
    // 调节参数个数,有些参数可以bind时写死
    function<int(int)> f3 = bind(Sub, 2, placeholders::_1);
    cout << f3(1);  // 2 - 1
}

现在就可以改进7.3中的代码了

cpp 复制代码
function<double(double, double)> f4 = bind(&Plus::PlusD, Plus(), placeholders::_1, placeholders::_2);
cout << f4(1.1, 2.2);

这样就可以简化调用传参

相关推荐
六点半88820 分钟前
【C++】 vector 迭代器失效问题
开发语言·c++·青少年编程
海海不掉头发25 分钟前
【已解决】如何使用JAVA 语言实现二分查找-二分搜索折半查找【算法】手把手学会二分查找【数据结构与算法】
java·开发语言·算法
_Power_Y1 小时前
浙大数据结构:05-树9 Huffman Codes
数据结构·c++·算法
Ljw...2 小时前
特殊类设计
c++
BeyondESH2 小时前
C++—单例设计模式
java·c++·设计模式
好奇的菜鸟2 小时前
探索 JUnit 5:下一代 Java 测试框架
java·开发语言·junit
林小果12 小时前
桥接模式
java·开发语言·设计模式
@月落3 小时前
PHP API 框架:构建高效API的利器
开发语言·php
情书4 小时前
Java调用第三方接口、http请求详解,一文学会
java·开发语言·http
Stark、4 小时前
C++入门day5-面向对象编程(终)
开发语言·c++·后端·学习方法