前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >【C++】C++11

【C++】C++11

作者头像
用户11290673
发布2025-02-05 08:23:06
发布2025-02-05 08:23:06
920
举报
文章被收录于专栏:学习学习

1.C++11的发展历史

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

2.列表初始化

2.1C++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.2C++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.3C++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 }; // the

type 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 ; }


3.右值引用与移动语义

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

3.1左值与右值

左值是⼀个表⽰数据的表达式(如变量名或解引⽤的指针),⼀般是有持久状态,存储在内存中,我

们可以获取它的地址,左值可以出现赋值符号的左边,也可以出现在赋值符号右边。定义时const

修饰符后的左值,不能给他赋值,但是可以取它的地址。

右值也是⼀个表⽰数据的表达式,要么是字⾯值常量、要么是表达式求值过程中创建的临时对象

等,右值可以出现在赋值符号的右边,但是不能出现出现在赋值符号的左边,右值不能取地址。

值得⼀提的是,左值的英⽂简写为lvalue,右值的英⽂简写为rvalue。传统认为它们分别是left

value、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

汇编层实现,底层都是⽤指针实现的,没什么区别。底层汇编等实现和上层语法表达的意义有时是

背离的,所以不要然到⼀起去理解,互相佐证,这样反⽽是陷⼊迷途。

template < class _Ty > remove_reference_t <_Ty>&& move (_Ty&& _Arg) { // forward _Arg as movable return static_cast < remove_reference_t <_Ty>&&>(_Arg); } # 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' ; 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 的左值引⽤也能延⻓临时对象⽣存期,但这些对象⽆法被修改。

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 ; }

3.5右值引用和移动语义的使用场景

3.5.1左值引用主要使用场景回顾

左值引⽤主要使⽤场景是在函数中左值引⽤传参和左值引⽤传返回值时减少拷⻉,同时还可以修改实参和修改返回对象的价值。左值引⽤已经解决⼤多数场景的拷⻉效率问题,但是有些场景不能使⽤传左值引⽤返回,如addStrings和generate函数,C++98中的解决⽅案只能是被迫使⽤输出型参数解决。那么C++11以后这⾥可以使⽤右值引⽤做返回值解决吗?显然是不可能的,因为这⾥的本质是返回对象是⼀个局部对象,函数结束这个对象就析构销毁了,右值引⽤返回也⽆法概念对象已经析构销毁的事实。

class Solution { public : // 传值返回需要拷⻉ string addStrings (string num1, string num2) { string str; int end1 = num1. size () -1 , end2 = num2. size () -1 ; // 进位 int next = 0 ; while (end1 >= 0 || end2 >= 0 ) { int val1 = end1 >= 0 ? num1[end1--]- '0' : 0 ; int val2 = end2 >= 0 ? num2[end2--]- '0' : 0 ; int ret = val1 + val2+next; next = ret / 10 ; ret = ret % 10 ; str += ( '0' +ret); } if (next == 1 ) str += '1' ; reverse (str. begin (), str. end ()); return str; } }; class Solution { public : // 这⾥的传值返回拷⻉代价就太⼤了 vector<vector< int >> generate ( int numRows) { vector<vector< int >> vv (numRows); for ( int i = 0 ; i < numRows; ++i) { vv[i]. resize (i+ 1 , 1 ); } for ( int i = 2 ; i < numRows; ++i) { for ( int j = 1 ; j < i; ++j) { vv[i][j] = vv[i -1 ][j] + vv[i -1 ][j -1 ]; } } return vv; } };

3.5.2移动构造和移动赋值

移动构造函数是⼀种构造函数,类似拷⻉构造函数,移动构造函数要求第⼀个参数是该类类型的引

⽤,但是不同的是要求这个参数是右值引⽤,如果还有其他参数,额外的参数必须有缺省值。

移动赋值是⼀个赋值运算符的重载,他跟拷⻉赋值构成函数重载,类似拷⻉赋值函数,移动赋值函

数要求第⼀个参数是该类类型的引⽤,但是不同的是要求这个参数是右值引⽤。

对于像string/vector这样的深拷⻉的类或者包含深拷⻉的成员变量的类,移动构造和移动赋值才有

意义,因为移动构造和移动赋值的第⼀个参数都是右值引⽤的类型,他的本质是要“窃取”引⽤的

右值对象的资源,⽽不是像拷⻉构造和拷⻉赋值那样去拷⻉资源,从提⾼效率。下⾯的bit::string

样例实现了移动构造和移动赋值,我们需要结合场景理解。

1# define _CRT_SECURE_NO_WARNINGS 1 2# include <iostream> 3# include <assert.h> 4# include <string.h> 5# include <algorithm> 6using namespace std; 7 8namespace bit 9 { 10 class string 11 { 12 public : 13 typedef char * iterator; 14 typedef const char * const_iterator; 15 16 iterator begin () 17 { 18 return _str; 19 } 20 iterator end () 21 { 22 return _str + _size; 23 } 24 25 const_iterator begin () const 26 { 27 return _str; 28 } 29 30 const_iterator end () const 31 { 32 return _str + _size; 33 } 34 35 string ( const char * str = "" ) 36 :_size( strlen (str)) 37 , _capacity(_size) 38 { 39 cout << "string(char* str)- 构造 " << endl; 40 _str = new char [_capacity + 1 ]; 41 strcpy (_str, str); 42 } 43 44 void swap (string& s) 45 { 46 :: swap (_str, s._str); 47 :: swap (_size, s._size); 48 :: swap (_capacity, s._capacity); 49 } 50 51 string ( const string& s) 52 :_str( nullptr ) 53 { 54 cout << "string(const string& s) -- 拷⻉构造 " << endl; 55 56 reserve (s._capacity); 57 for ( auto ch : s) 58 { 59 push_back (ch); 60 } 61 } 62 63 // 移动构造 64 string (string&& s) 65 { 66 cout << "string(string&& s) -- 移动构造 " << endl; 67 swap (s); 68 } 69 70 string& operator =( const string& s) 71 { 72 cout << "string& operator=(const string& s) -- 拷⻉赋值 " << endl; 73 if ( this != &s) 74 { 75 _str[ 0 ] = '\0' ; 76 _size = 0 ; 77 78 reserve (s._capacity); 79 for ( auto ch : s) 80 { 81 push_back (ch); 82 } 83 } 84 85 return * this ; 86 } 87 88 // 移动赋值 89 string& operator =(string&& s) 90 { 91 cout << "string& operator=(string&& s) -- 移动赋值 " << endl; 92 swap (s); 93 return * this ; 94 } 95 96 ~ string () 97 { 98 cout << "~string() -- 析构 " << endl; 99 delete [] _str; 100 _str = nullptr ; 101 } 102 103 char & operator []( size_t pos) 104 { 105 assert (pos < _size); 106 return _str[pos]; 107 } 108 109 void reserve ( size_t n) 110 { 111 if (n > _capacity) 112 { 113 char * tmp = new char [n + 1 ]; 114 if (_str) 115 { 116 strcpy (tmp, _str); 117 delete [] _str; 118 } 119 _str = tmp; 120 _capacity = n; 121 } 122 } 123 124 void push_back ( char ch) 125 { 126 if (_size >= _capacity) 127 { 128 size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2 ; 129 reserve (newcapacity); 130 } 131 132 _str[_size] = ch; 133 ++_size; 134 _str[_size] = '\0' ; 135 } 136 137 string& operator +=( char ch) 138 { 139 push_back (ch); 140 return * this ; 141 } 142 143 const char * c_str () const 144 { 145 return _str; 146 } 147 148 size_t size () const 149 { 150 return _size; 151 } 152 private : 153 char * _str = nullptr ; 154 size_t _size = 0 ; 155 size_t _capacity = 0 ; 156 }; 157 } 158 159 int main () 160 { 161 bit::string s1 ( "xxxxx" ); 162 // 拷⻉构造 163 bit::string s2 = s1; 164 // 构造 + 移动构造,优化后直接构造 165 bit::string s3 = bit:: string ( "yyyyy" ); 166 // 移动构造 167 bit::string s4 = move (s1); 168 cout << "******************************" << endl; 169 170 return 0 ; 171 }

3.5.3右值引用和移动语义解决传值返回问题

namespace bit { string addStrings (string num1, string num2) { string str; int end1 = num1. size () - 1 , end2 = num2. size () - 1 ; int next = 0 ; while (end1 >= 0 || end2 >= 0 ) { int val1 = end1 >= 0 ? num1[end1--] - '0' : 0 ; int val2 = end2 >= 0 ? num2[end2--] - '0' : 0 ; int ret = val1 + val2 + next; next = ret / 10 ; ret = ret % 10 ; str += ( '0' + ret); } if (next == 1 ) str += '1' ; reverse (str. begin (), str. end ()); cout << "******************************" << endl; return str; } } // 场景 1 int main () { bit::string ret = bit:: addStrings ( "11111" , "2222" ); cout << ret. c_str () << endl; return 0 ; } // 场景 2 int main () { bit::string ret; ret = bit:: addStrings ( "11111" , "2222" ); cout << ret. c_str () << endl; return 0 ; }


3.6类型分类

C++11以后,进⼀步对类型进⾏了划分,右值被划分纯右值(pure value,简称prvalue)和将亡值

(expiring value,简称xvalue)。

纯右值是指那些字⾯值常量或求值结果相当于字⾯值或是⼀个不具名的临时对象。如: 42 、

true 、 nullptr 或者类似 str.substr(1, 2) 、 str1 + str2 传值返回函数调⽤,或者整

形 a 、 b , a++ , a+b 等。纯右值和将亡值C++11中提出的,C++11中的纯右值概念划分等价于

C++98中的右值。

将亡值是指返回右值引⽤的函数的调⽤表达式和转换为右值引⽤的转换函数的调⽤表达,如

move(x) 、 static_cast<X&&>(x)

泛左值(generalized value,简称glvalue),泛左值包含将亡值和左值。

3.7引用折叠

C++中不能直接定义引⽤的引⽤如 int& && r = i; ,这样写会直接报错,通过模板或 typedef

中的类型操作可以构成引⽤的引⽤。

通过模板或 typedef 中的类型操作可以构成引⽤的引⽤时,这时C++11给出了⼀个引⽤折叠的规

则:右值引⽤的右值引⽤折叠成右值引⽤,所有其他组合均折叠成左值引⽤。

下⾯的程序中很好的展⽰了模板和typedef时构成引⽤的引⽤时的引⽤折叠规则,⼤家需要⼀个⼀

个仔细理解⼀下。

像f2这样的函数模板中,T&& x参数看起来是右值引⽤参数,但是由于引⽤折叠的规则,他传递左

值时就是左值引⽤,传递右值时就是右值引⽤,有些地⽅也把这种函数模板的参数叫做万能引⽤。

Function(T&& t)函数模板程序中,假设实参是int右值,模板参数T的推导int,实参是int左值,模

板参数T的推导int&,再结合引⽤折叠规则,就实现了实参是左值,实例化出左值引⽤版本形参的

Function,实参是右值,实例化出右值引⽤版本形参的Function。

// 由于引⽤折叠限定, f1 实例化以后总是⼀个左值引⽤ template < class T> void f1 (T& x) {} // 由于引⽤折叠限定, f2 实例化后可以是左值引⽤,也可以是右值引⽤ template < class T> void f2 (T&& x) {} int main () { typedef int & lref; typedef int && rref; int n = 0 ; lref& r1 = n; // r1 的类型是 int& lref&& r2 = n; // r2 的类型是 int& rref& r3 = n; // r3 的类型是 int& rref&& r4 = 1 ; // r4 的类型是 int&& // 没有折叠 -> 实例化为 void f1(int& x) f1 < int >(n); f1 < int >( 0 ); // 报错 // 折叠 -> 实例化为 void f1(int& x) f1 < int &>(n); f1 < int &>( 0 ); // 报错 // 折叠 -> 实例化为 void f1(int& x) f1 < int &&>(n); f1 < int &&>( 0 ); // 报错 // 折叠 -> 实例化为 void f1(const int& x) f1 < const int &>(n); f1 < const int &>( 0 ); // 折叠 -> 实例化为 void f1(const int& x) f1 < const int &&>(n); f1 < const int &&>( 0 ); // 没有折叠 -> 实例化为 void f2(int&& x) f2 < int >(n); // 报错 f2 < int >( 0 ); // 折叠 -> 实例化为 void f2(int& x) f2 < int &>(n); f2 < int &>( 0 ); // 报错 // 折叠 -> 实例化为 void f2(int&& x) f2 < int &&>(n); // 报错 f2 < int &&>( 0 ); return 0 ; }

1 template < class T> 2 void Function (T&& t) 3 { 4 int a = 0 ; 5 T x = a; 6 //x++; 7 cout << &a << endl; 8 cout << &x << endl << endl; 9 } 10 11 int main () 12 { 13 // 10 是右值,推导出 T int ,模板实例化为 void Function(int&& t) 14 Function ( 10 ); // 右值 15 16 int a; 17 // a 是左值,推导出 T int& ,引⽤折叠,模板实例化为 void Function(int& t) 18 Function (a); // 左值 19 20 // std::move(a) 是右值,推导出 T int ,模板实例化为 void Function(int&& t) 21 Function (std:: move (a)); // 右值 22 23 const int b = 8 ; 24 // a 是左值,推导出 T const int& ,引⽤折叠,模板实例化为 void Function(const int& t) 25 // 所以 Function 内部会编译报错, x 不能 ++ 26 Function (b); // const 左值 27 // std::move(b) 右值,推导出 T const int ,模板实例化为 void Function(const int&& t) // 所以 Function 内部会编译报错, x 不能 ++ Function (std:: move (b)); // const 右值 return 0 ; }

3.8完美转发

Function(T&& t)函数模板程序中,传左值实例化以后是左值引⽤的Function函数,传右值实例化

以后是右值引⽤的Function函数。

但是结合我们在3.2章节的讲解,变量表达式都是左值属性,也就意味着⼀个右值被右值引⽤绑定

后,右值引⽤变量表达式的属性是左值,也就是说Function函数中t的属性是左值,那么我们把t传

递给下⼀层函数Fun,那么匹配的都是左值引⽤版本的Fun函数。这⾥我们想要保持t对象的属性,

就需要使⽤完美转发实现。

template <class T> T&& forward (typename remove_reference<T>::type&

arg);

template <class T> T&& forward (typename

remove_reference<T>::type&& arg) ;

完美转发forward本质是⼀个函数模板,他主要还是通过引⽤折叠的⽅式实现,下⾯⽰例中传递给

Function的实参是右值,T被推导为int,没有折叠,forward内部t被强转为右值引⽤返回;传递给

Function的实参是左值,T被推导为int&,引⽤折叠为左值引⽤,forward内部t被强转为左值引⽤

返回。

template < class _Ty > _Ty&& forward ( remove_reference_t <_Ty>& _Arg) noexcept { // forward an lvalue as either an lvalue or an rvalue return static_cast <_Ty&&>(_Arg); } 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 < class T> void Function (T&& t) { Fun (t); //Fun(forward<T>(t)); } int main () { // 10 是右值,推导出 T int ,模板实例化为 void Function(int&& t) Function ( 10 ); // 右值 int a; // a 是左值,推导出 T int& ,引⽤折叠,模板实例化为 void Function(int& t) Function (a); // 左值 // std::move(a) 是右值,推导出 T int ,模板实例化为 void Function(int&& t) Function (std:: move (a)); // 右值 const int b = 8 ; // a 是左值,推导出 T const int& ,引⽤折叠,模板实例化为 void Function(const int& t) Function (b); // const 左值 // std::move(b) 右值,推导出 T const int ,模板实例化为 void Function(const int&& t) Function (std:: move (b)); // const 右值 return 0 ; }


4.可变模版参数

4.1基本语法及原理

C++11⽀持可变参数模板,也就是说⽀持可变数量参数的函数模板和类模板,可变数⽬的参数被称

为参数包,存在两种参数包:模板参数包,表⽰零或多个模板参数;函数参数包:表⽰零或多个函

数参数。

template <class ...Args> void Func(Args... args) {}

template <class ...Args> void Func(Args&... args) {}

template <class ...Args> void Func(Args&&... args) {}

我们⽤省略号来指出⼀个模板参数或函数参数的表⽰⼀个包,在模板参数列表中,class...或

typename...指出接下来的参数表⽰零或多个类型列表;在函数参数列表中,类型名后⾯跟...指出

接下来表⽰零或多个形参对象列表;函数参数包可以⽤左值引⽤或右值引⽤表⽰,跟前⾯普通模板

⼀样,每个参数实例化时遵循引⽤折叠规则。

可变参数模板的原理跟模板类似,本质还是去实例化对应类型和个数的多个函数。

这⾥我们可以使⽤sizeof...运算符去计算参数包中参数的个数。

template < class ...Args> void Print (Args&&... args) { cout << sizeof ...(args) << endl; } int main () { double x = 2.2 ; Print (); // 包⾥有 0 个参数 Print ( 1 ); // 包⾥有 1 个参数 Print ( 1 , string ( "xxxxx" )); // 包⾥有 2 个参数 Print ( 1.1 , string ( "xxxxx" ), x); // 包⾥有 3 个参数 return 0 ; } // 原理 1 :编译本质这⾥会结合引⽤折叠规则实例化出以下四个函数 void Print (); void Print ( int && arg1); void Print ( int && arg1, string&& arg2); void Print ( double && arg1, string&& arg2, double & arg3); // 原理 2 :更本质去看没有可变参数模板,我们实现出这样的多个函数模板才能⽀持 // 这⾥的功能,有了可变参数模板,我们进⼀步被解放,他是类型泛化基础 // 上叠加数量变化,让我们泛型编程更灵活。 void Print (); template < class T1 > void Print (T1&& arg1); template < class T1 , class T2 > void Print (T1&& arg1, T2&& arg2); template < class T1 , class T2 , class T3 > void Print (T1&& arg1, T2&& arg2, T3&& arg3); // ...

4.2包扩展

对于⼀个参数包,我们除了能计算他的参数个数,我们能做的唯⼀的事情就是扩展它,当扩展⼀个

包时,我们还要提供⽤于每个扩展元素的模式,扩展⼀个包就是将它分解为构成的元素,对每个元

素应⽤模式,获得扩展后的列表。我们通过在模式的右边放⼀个省略号(...)来触发扩展操作。底层

的实现细节如图1所⽰。

C++还⽀持更复杂的包扩展,直接将参数包依次展开依次作为实参给⼀个函数去处理。

1// 可变模板参数 2// 参数类型可变 3// 参数个数可变 4// 打印参数包内容 5//template <class ...Args> 6//void Print(Args... args) 7//{ 8// // 可变参数模板编译时解析 9// // 下⾯是运⾏获取和解析,所以不⽀持这样⽤ 10// cout << sizeof...(args) << endl; 11// for (size_t i = 0; i < sizeof...(args); i++) 12// { 13// cout << args[i] << " "; 14// } 15 // cout << endl; 16 //} 17 18 void ShowList () 19 { 20 // 编译器时递归的终⽌条件,参数包是 0 个时,直接匹配这个函数 21 cout << endl; 22 } 23 24 template < class T , class ...Args> 25 void ShowList (T x, Args... args) 26 { 27 cout << x << " " ; 28 // args N 个参数的参数包 29 // 调⽤ ShowList ,参数包的第⼀个传给 x ,剩下 N-1 传给第⼆个参数包 30 ShowList (args...); 31 } 32 33 // 编译时递归推导解析参数 34 template < class ...Args> 35 void Print (Args... args) 36 { 37 ShowList (args...); 38 } 39 40 int main () 41 { 42 Print (); 43 Print ( 1 ); 44 Print ( 1 , string ( "xxxxx" )); 45 Print ( 1 , string ( "xxxxx" ), 2.2 ); 46 47 return 0 ; 48 } 49 50 //template <class T, class ...Args> 51 //void ShowList(T x, Args... args) 52 //{ 53 // cout << x << " "; 54 // Print(args...); 55 //} 56 57 // Print(1, string("xxxxx"), 2.2); 调⽤时 58 // 本质编译器将可变参数模板通过模式的包扩展,编译器推导的以下三个重载函数函数 59 //void ShowList(double x) 60 //{ 61 // cout << x << " "; 62 // ShowList(); 63 //} 64 // 65 //void ShowList(string x, double z) 66 //{ 67 // cout << x << " "; 68 // ShowList(z); 69 //} 70 // 71 //void ShowList(int x, string y, double z) 72 //{ 73 // cout << x << " "; 74 // ShowList(y, z); 75 //} 76 77 //void Print(int x, string y, double z) 78 //{ 79 // ShowList(x, y, z); 80 //}

1 template < class T > 2 const T& GetArg ( const T& x) 3 { 4 cout << x << " " ; 5 return x; 6 } 7 8 template < class ...Args> 9 void Arguments (Args... args) 10 {} 11 12 template < class ...Args> 13 void Print (Args... args) 14 { 15 // 注意 GetArg 必须返回或者到的对象,这样才能组成参数包给 Arguments 16 Arguments ( GetArg (args)...); 17 } 18 19 // 本质可以理解为编译器编译时,包的扩展模式 20 // 将上⾯的函数模板扩展实例化为下⾯的函数 21 // 是不是很抽象, C++11 以后,只能说委员会的⼤佬设计语法思维跳跃得太厉害 22 //void Print(int x, string y, double z) 23 //{ 24 // Arguments(GetArg(x), GetArg(y), GetArg(z)); 25 //} int main () { Print ( 1 , string ( "xxxxx" ), 2.2 ); return 0 ; }

4.3empalce系列接口

template <class... Args> void emplace_back (Args&&... args);

template <class... Args> iterator emplace (const_iterator position,

Args&&... args);

C++11以后STL容器新增了empalce系列的接⼝,empalce系列的接⼝均为模板可变参数,功能上

兼容push和insert系列,但是empalce还⽀持新玩法,假设容器为container<T>,empalce还⽀持

直接插⼊构造T对象的参数,这样有些场景会更⾼效⼀些,可以直接在容器空间上构造T对象。

emplace_back总体⽽⾔是更⾼效,推荐以后使⽤emplace系列替代insert和push系列

第⼆个程序中我们模拟实现了list的emplace和emplace_back接⼝,这⾥把参数包不段往下传递,

最终在结点的构造中直接去匹配容器存储的数据类型T的构造,所以达到了前⾯说的empalce⽀持

直接插⼊构造T对象的参数,这样有些场景会更⾼效⼀些,可以直接在容器空间上构造T对象。

传递参数包过程中,如果是 Args&&... args 的参数包,要⽤完美转发参数包,⽅式如下

std::forward<Args>(args)... ,否则编译时包扩展后右值引⽤变量表达式就变成了左

值。

1# include <list> 2// emplace_back 总体⽽⾔是更⾼效,推荐以后使⽤ emplace 系列替代 insert push 系列 3int main () 4{ 5list<bit::string> lt; 6// 传左值,跟 push_back ⼀样,⾛拷⻉构造 7bit::string s1 ( "111111111111" ); 8lt. emplace_back (s1); 9cout << "*********************************" << endl; 10// 右值,跟 push_back ⼀样,⾛移动构造 11lt. emplace_back ( move (s1)); 12cout << "*********************************" << endl; 13// 直接把构造 string 参数包往下传,直接⽤ string 参数包构造 string 14// 这⾥达到的效果是 push_back 做不到的 15lt. emplace_back ( "111111111111" ); 19 cout << "*********************************" << endl; 20 21 list<pair<bit::string, int >> lt1; 22 // push_back ⼀样 23 // 构造 pair + 拷⻉ / 移动构造 pair list 的节点中 data 24 pair<bit::string, int > kv ( " 苹果 " , 1 ); 25 lt1. emplace_back (kv); 26 cout << "*********************************" << endl; 27 28 // push_back ⼀样 29 lt1. emplace_back ( move (kv)); 30 cout << "*********************************" << endl; 31 32 33 // 直接把构造 pair 参数包往下传,直接⽤ pair 参数包构造 pair 34 // 这⾥达到的效果是 push_back 做不到的 35 lt1. emplace_back ( " 苹果 " , 1 ); 36 cout << "*********************************" << endl; 37 38 return 0 ; 39 }

1 // List.h 2 namespace bit 3 { 4 template < class T > 5 struct ListNode 6 { 7 ListNode<T>* _next; 8 ListNode<T>* _prev; 9 10 T _data; 11 12 ListNode (T&& data) 13 :_next( nullptr ) 14 , _prev( nullptr ) 15 , _data( move (data)) 16 {} 17 18 template < class ... Args> 19 ListNode (Args&&... args) 20 : _next( nullptr ) 21 , _prev( nullptr ) 22 , _data(std::forward<Args>(args)...) 23 {} 24 }; 25 26 template < class T , class Ref , class Ptr > 27 struct ListIterator 28 { 29 typedef ListNode<T> Node; 30 typedef ListIterator<T, Ref, Ptr> Self; 31 Node* _node; 32 33 ListIterator (Node* node) 34 :_node(node) 35 {} 36 37 // ++it; 38 Self& operator ++() 39 { 40 _node = _node->_next; 41 return * this ; 42 } 43 44 Self& operator --() 45 { 46 _node = _node->_prev; 47 return * this ; 48 } 49 50 Ref operator *() 51 { 52 return _node->_data; 53 } 54 55 bool operator !=( const Self& it) 56 { 57 return _node != it._node; 58 } 59 }; 60 61 template < class T > 62 class list 63 { 64 typedef ListNode<T> Node; 65 public : 66 typedef ListIterator<T, T&, T*> iterator; 67 typedef ListIterator<T, const T&, const T*> const_iterator; 68 69 iterator begin () 70 { 71 return iterator (_head->_next); 72 } 73 74 iterator end () 75 { 76 return iterator (_head); 77 } 78 79 void empty_init () 80 { 81 _head = new Node (); 82 _head->_next = _head; 83 _head->_prev = _head; 84 } 85 86 list () 87 { 88 empty_init (); 89 } 90 91 void push_back ( const T& x) 92 { 93 insert ( end (), x); 94 } 95 96 void push_back (T&& x) 97 { 98 insert ( end (), move (x)); 99 } 100 101 iterator insert (iterator pos, const T& x) 102 { 103 Node* cur = pos._node; 104 Node* newnode = new Node (x); 105 Node* prev = cur->_prev; 106 107 // prev newnode cur 108 prev->_next = newnode; 109 newnode->_prev = prev; 110 newnode->_next = cur; 111 cur->_prev = newnode; 112 113 return iterator (newnode); 114 } 115 116 iterator insert (iterator pos, T&& x) 117 { 118 Node* cur = pos._node; 119 Node* newnode = new Node ( move (x)); 120 Node* prev = cur->_prev; 121 122 // prev newnode cur 123 prev->_next = newnode; 124 newnode->_prev = prev; 125 newnode->_next = cur; 126 cur->_prev = newnode; 127 128 return iterator (newnode); 129 } 130 131 template < class ... Args> 132 void emplace_back (Args&&... args) 133 { 134 insert ( end (), std::forward<Args>(args)...); 135 } 136 137 // 原理:本质编译器根据可变参数模板⽣成对应参数的函数 138 /*void emplace_back(string& s) 139 { 140 insert(end(), std::forward<string>(s)); 141 } 142 143 void emplace_back(string&& s) 144 { 145 insert(end(), std::forward<string>(s)); 146 } 147 148 void emplace_back(const char* s) 149 { 150 insert(end(), std::forward<const char*>(s)); 151 } 152 */ 153 154 template < class ... Args> 155 iterator insert (iterator pos, Args&&... args) 156 { 157 Node* cur = pos._node; 158 Node* newnode = new Node (std::forward<Args>(args)...); 159 Node* prev = cur->_prev; 160 161 // prev newnode cur 162 prev->_next = newnode; 163 newnode->_prev = prev; 164 newnode->_next = cur; 165 cur->_prev = newnode; 166 167 return iterator (newnode); 168 } 169 private : 170 Node* _head; 171 }; 172 } 173 174 // Test.cpp 175 # include "List.h" 176 177 // emplace_back 总体⽽⾔是更⾼效,推荐以后使⽤ emplace 系列替代 insert push 系列 178 int main () 179 { 180 bit::list<bit::string> lt; 181 // 传左值,跟 push_back ⼀样,⾛拷⻉构造 182 bit::string s1 ( "111111111111" ); 183 lt. emplace_back (s1); 184 cout << "*********************************" << endl; 185 186 // 右值,跟 push_back ⼀样,⾛移动构造 187 lt. emplace_back ( move (s1)); 188 cout << "*********************************" << endl; 189 190 // 直接把构造 string 参数包往下传,直接⽤ string 参数包构造 string 191 // 这⾥达到的效果是 push_back 做不到的 192 lt. emplace_back ( "111111111111" ); 193 cout << "*********************************" << endl; 194 195 bit::list<pair<bit::string, int >> lt1; 196 // push_back ⼀样 197 // 构造 pair + 拷⻉ / 移动构造 pair list 的节点中 data 198 pair<bit::string, int > kv ( " 苹果 " , 1 ); 199 lt1. emplace_back (kv); 200 cout << "*********************************" << endl; 201 202 // push_back ⼀样 203 lt1. emplace_back ( move (kv)); 204 cout << "*********************************" << endl; 205 206 207 // 直接把构造 pair 参数包往下传,直接⽤ pair 参数包构造 pair 208 // 这⾥达到的效果是 push_back 做不到的 209 lt1. emplace_back ( " 苹果 " , 1 ); 210 cout << "*********************************" << endl; 211 return 0 ; } 212 213


5.新的类功能

5.1默认的移动构造和移动赋值

原来C++类中,有6个默认成员函数:构造函数/析构函数/拷⻉构造函数/拷⻉赋值重载/取地址重

载/const 取地址重载,最后重要的是前4个,后两个⽤处不⼤,默认成员函数就是我们不写编译器

会⽣成⼀个默认的。C++11 新增了两个默认成员函数,移动构造函数和移动赋值运算符重载。

如果你没有⾃⼰实现移动构造函数,且没有实现析构函数 、拷⻉构造、拷⻉赋值重载中的任意⼀

个。那么编译器会⾃动⽣成⼀个默认移动构造。默认⽣成的移动构造函数,对于内置类型成员会执

⾏逐成员按字节拷⻉,⾃定义类型成员,则需要看这个成员是否实现移动构造,如果实现了就调⽤

移动构造,没有实现就调⽤拷⻉构造。

如果你没有⾃⼰实现移动赋值重载函数,且没有实现析构函数 、拷⻉构造、拷⻉赋值重载中的任意⼀个,那么编译器会⾃动⽣成⼀个默认移动赋值。默认⽣成的移动构造函数,对于内置类型成员会执⾏逐成员按字节拷⻉,⾃定义类型成员,则需要看这个成员是否实现移动赋值,如果实现了就调⽤移动赋值,没有实现就调⽤拷⻉赋值。(默认移动赋值跟上⾯移动构造完全类似)

如果你提供了移动构造或者移动赋值,编译器不会⾃动提供拷⻉构造和拷⻉赋值。

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 : 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 ; }

5.2defult和delete

C++11可以让你更好的控制要使⽤的默认函数。假设你要使⽤某个默认的函数,但是因为⼀些原因

这个函数没有默认⽣成。⽐如:我们提供了拷⻉构造,就不会⽣成移动构造了,那么我们可以使⽤

default关键字显⽰指定移动构造⽣成。

如果能想要限制某些默认函数的⽣成,在C++98中,是该函数设置成private,并且只声明补丁已,

这样只要其他⼈想要调⽤就会报错。在C++11中更简单,只需在该函数声明加上=delete即可,该语法指⽰编译器不⽣成对应函数的默认版本,称=delete修饰的函数为删除函数。

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 (Person&& p) = default ; //Person(const Person& p) = delete; private : bit::string _name; int _age; }; int main () { Person s1; Person s2 = s1; Person s3 = std:: move (s1); return 0 ; }


6.STL中⼀些变化

下图1圈起来的就是STL中的新容器,但是实际最有⽤的是unordered_map和unordered_set。这

两个我们前⾯已经进⾏了⾮常详细的讲解,其他的⼤家了解⼀下即可。

STL中容器的新接⼝也不少,最重要的就是右值引⽤和移动语义相关的push/insert/emplace系列

接⼝和移动构造和移动赋值,还有initializer_list版本的构造等,这些前⾯都讲过了,还有⼀些⽆关

痛痒的如cbegin/cend等需要时查查⽂档即可。

容器的范围for遍历,这个在容器部分也总结过了。


7.lambda

7.1lambda表达式语法

lambda 表达式本质是⼀个匿名函数对象,跟普通函数不同的是他可以定义在函数内部。

lambda 表达式语法使⽤层⽽⾔没有类型,所以我们⼀般是⽤auto或者模板参数定义的对象去接

收 lambda 对象。

lambda表达式的格式: [capture-list] (parameters)-> return type {

function boby }

[capture-list] : 捕捉列表,该列表总是出现在 lambda 函数的开始位置,编译器根据[]来

判断接下来的代码是否为 lambda 函数,捕捉列表能够捕捉上下⽂中的变量供 lambda 函数使

⽤,捕捉列表可以传值和传引⽤捕捉,具体细节7.2中我们再细说。捕捉列表为空也不能省略。

(parameters) :参数列表,与普通函数的参数列表功能类似,如果不需要参数传递,则可以连

同()⼀起省略

->return type :返回值类型,⽤追踪返回类型形式声明函数的返回值类型,没有返回值时此

部分可省略。⼀般返回值类型明确情况下,也可省略,由编译器对返回类型进⾏推导。

{function boby} :函数体,函数体内的实现跟普通函数完全类似,在该函数体内,除了可以

使⽤其参数外,还可以使⽤所有捕获到的变量,函数体为空也不能省略。

int main () { // ⼀个简单的 lambda 表达式 auto add1 = []( int x, int y)-> int { return x + y; }; cout << add1 ( 1 , 2 ) << endl; // 1 、捕捉为空也不能省略 // 2 、参数为空可以省略 // 3 、返回值可以省略,可以通过返回对象⾃动推导 // 4 、函数题不能省略 auto func1 = [] { cout << "hello bit" << endl; return 0 ; }; func1 (); int a = 0 , b = 1 ; auto swap1 = []( int & x, int & y) { int tmp = x; x = y; y = tmp; }; swap1 (a, b); cout << a << ":" << b << endl; return 0 ; }

7.2捕捉列表

lambda 表达式中默认只能⽤ lambda 函数体和参数中的变量,如果想⽤外层作⽤域中的变量就

需要进⾏捕捉

第⼀种捕捉⽅式是在捕捉列表中显⽰的传值捕捉和传引⽤捕捉,捕捉的多个变量⽤逗号分割。[x,

y, &z] 表⽰x和y值捕捉,z引⽤捕捉。

第⼆种捕捉⽅式是在捕捉列表中隐式捕捉,我们在捕捉列表写⼀个=表⽰隐式值捕捉,在捕捉列表

写⼀个&表⽰隐式引⽤捕捉,这样我们 lambda 表达式中⽤了那些变量,编译器就会⾃动捕捉那些

变量。

第三种捕捉⽅式是在捕捉列表中混合使⽤隐式捕捉和显⽰捕捉。[=, &x]表⽰其他变量隐式值捕捉,

x引⽤捕捉;[&, x, y]表⽰其他变量引⽤捕捉,x和y值捕捉。当使⽤混合捕捉时,第⼀个元素必须是

&或=,并且&混合捕捉时,后⾯的捕捉变量必须是值捕捉,同理=混合捕捉时,后⾯的捕捉变量必

须是引⽤捕捉。

lambda 表达式如果在函数局部域中,他可以捕捉 lambda 位置之前定义的变量,不能捕捉静态

局部变量和全局变量,静态局部变量和全局变量也不需要捕捉, lambda 表达式中可以直接使

⽤。这也意味着 lambda 表达式如果定义在全局位置,捕捉列表必须为空。

默认情况下, lambda 捕捉列表是被const修饰的,也就是说传值捕捉的过来的对象不能修改,

mutable加在参数列表的后⾯可以取消其常量性,也就说使⽤该修饰符后,传值捕捉的对象就可以

修改了,但是修改还是形参对象,不会影响实参。使⽤该修饰符后,参数列表不可省略(即使参数为空)。

int x = 0 ; // 捕捉列表必须为空,因为全局变量不⽤捕捉就可以⽤,没有可被捕捉的变量 auto func1 = []() { x++; }; int main () { // 只能⽤当前 lambda 局部域和捕捉的对象和全局对象 int a = 0 , b = 1 , c = 2 , d = 3 ; auto func1 = [a, &b] { // 值捕捉的变量不能修改,引⽤捕捉的变量可以修改 //a++; b++; int ret = a + b; return ret; }; cout << func1 () << endl; // 隐式值捕捉 // ⽤了哪些变量就捕捉哪些变量 auto func2 = [=] { int ret = a + b + c; return ret; }; cout << func2 () << endl; // 隐式引⽤捕捉 // ⽤了哪些变量就捕捉哪些变量 auto func3 = [&] { a++; c++; d++; }; func3 (); cout << a << " " << b << " " << c << " " << d <<endl; // 混合捕捉 1 auto func4 = [&, a, b] { //a++; //b++; c++; d++; return a + b + c + d; }; func4 (); cout << a << " " << b << " " << c << " " << d << endl; // 混合捕捉 1 auto func5 = [=, &a, &b] { a++; b++; /*c++; d++;*/ return a + b + c + d; }; func5 (); cout << a << " " << b << " " << c << " " << d << endl; // 局部的静态和全局变量不能捕捉,也不需要捕捉 static int m = 0 ; auto func6 = [] { int ret = x + m; return ret; }; // 传值捕捉本质是⼀种拷⻉ , 并且被 const 修饰了 // mutable 相当于去掉 const 属性,可以修改了 // 但是修改了不会影响外⾯被捕捉的值,因为是⼀种拷⻉ auto func7 = [=]() mutable { a++; b++; c++; d++; return a + b + c + d; }; cout << func7 () << endl; cout << a << " " << b << " " << c << " " << d << endl; return 0 ; }

7.3lambda的应用

在学习 lambda 表达式之前,我们的使⽤的可调⽤对象只有函数指针和仿函数对象,函数指针的

类型定义起来⽐较⿇烦,仿函数要定义⼀个类,相对会⽐较⿇烦。使⽤ lambda 去定义可调⽤对

象,既简单⼜⽅便。

lambda 在很多其他地⽅⽤起来也很好⽤。⽐如线程中定义线程的执⾏函数逻辑,智能指针中定

制删除器等, lambda 的应⽤还是很⼴泛的,以后我们会不断接触到。

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 } }; // 类似这样的场景,我们实现仿函数对象或者函数指针⽀持商品中 // 不同项的⽐较,相对还是⽐较⿇烦的,那么这⾥ lambda 就很好⽤了 sort (v. begin (), v. end (), ComparePriceLess ()); sort (v. begin (), v. end (), ComparePriceGreater ()); 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._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 ; }

7.4lambda的原理

lambda 的原理和范围for很像,编译后从汇编指令层的⻆度看,压根就没有 lambda 和范围for

这样的东西。范围for底层是迭代器,⽽lambda底层是仿函数对象,也就说我们写了⼀个

lambda 以后,编译器会⽣成⼀个对应的仿函数的类。

仿函数的类名是编译按⼀定规则⽣成的,保证不同的 lambda ⽣成的类名不同,lambda参数/返

回类型/函数体就是仿函数operator()的参数/返回类型/函数体, lambda 的捕捉列表本质是⽣成

的仿函数类的成员变量,也就是说捕捉列表的变量都是 lambda 类构造函数的实参,当然隐式捕

捉,编译器要看使⽤哪些就传那些对象。

上⾯的原理,我们可以透过汇编层了解⼀下,下⾯第⼆段汇编层代码印证了上⾯的原理。

1 class Rate 2 { 3 public : 4 Rate ( double rate) 5 : _rate(rate) 6 {} 7 8 double operator ()( double money, int year) 9 { 10 return money * _rate * year; 11 } 12 13 private : 14 double _rate; 15 }; 16 17 int main () 18 { 19 double rate = 0.49 ; 20 21 // lambda 22 auto r2 = [rate]( double money, int year) { 23 return money * rate * year; 24 }; 25 26 // 函数对象 27 Rate r1 (rate); 28 r1 ( 10000 , 2 ); 29 30 r2 ( 10000 , 2 ); 31 32 auto func1 = [] { 33 cout << "hello world" << endl; 34 }; 35 func1 (); 36 37 return 0 ; 38 } 39

1 // lambda 2 auto r2 = [rate]( double money, int year) { 3 return money * rate * year; 4 }; 5 // 捕捉列表的 rate ,可以看到作为 lambda_1 类构造函数的参数传递了,这样要拿去初始化成员变量 6 // 下⾯ operator() 中才能使⽤ 7 00 D8295C lea eax,[rate] 8 00 D8295F push eax 9 00 D82960 lea ecx,[r2] 10 00 D82963 call `main ' ::` 2' ::<lambda_1>::<lambda_1> ( 0 D81F80h) 11 12 // 函数对象 13 Rate r1 (rate); 14 00 D82968 sub esp, 8 15 00 D8296B movsd xmm0,mmword ptr [rate] 16 00 D82970 movsd mmword ptr [esp],xmm0 17 00 D82975 lea ecx,[r1] 18 00 D82978 call Rate::Rate ( 0 D81438h) 19 r1 ( 10000 , 2 ); 20 00 D8297D push 2 21 00 D8297F sub esp, 8 22 00 D82982 movsd xmm0,mmword ptr [__real@ 40 c3880000000000 ( 0 D89B50h)] 23 00 D8298A movsd mmword ptr [esp],xmm0 24 00 D8298F lea ecx,[r1] 25 00 D82992 call Rate::operator () ( 0 D81212h) 26 27 // 汇编层可以看到 r2 lambda 对象调⽤本质还是调⽤ operator() ,类型是 lambda_1, 这个类型名 28 // 的规则是编译器⾃⼰定制的,保证不同的 lambda 不冲突 29 r2 ( 10000 , 2 ); 30 00 D82999 push 2 31 00 D8299B sub esp, 8 32 00 D8299E movsd xmm0,mmword ptr [__real@ 40 c3880000000000 ( 0 D89B50h)] 33 00 D829A6 movsd mmword ptr [esp],xmm0 34 00 D829AB lea ecx,[r2] 35 00 D829AE call `main ' ::` 2' ::<lambda_1>:: operator () ( 0 D824C0h)


8.包装器

8.1function

1 template < class T > 2 class function ; // undefined 3 4 template < class Ret , class ... Args> 5 class function < Ret (Args...)>;

std::function 是⼀个类模板,也是⼀个包装器。 std::function 的实例对象可以包装存

储其他的可以调⽤对象,包括函数指针、仿函数、 lambda 、 bind 表达式等,存储的可调⽤对

象被称为 std::function 的 ⽬标 。若 std::function 不含⽬标,则称它为 。调⽤

std::function 的 ⽬标 导致抛出 std::bad_function_call 异常。

以上是 function 的原型,他被定义<functional>头⽂件中。std::function - cppreference.com

是function的官⽅⽂件链接。

函数指针、仿函数、 lambda 等可调⽤对象的类型各不相同, std::function 的优势就是统

⼀类型,对他们都可以进⾏包装,这样在很多地⽅就⽅便声明可调⽤对象的类型,下⾯的第⼆个代

码样例展⽰了 std::function 作为map的参数,实现字符串和可调⽤对象的映射表功能。

# include <functional> int f ( int a, int b) { return a + b; } struct Functor { public : int operator () ( int a, int b) { return a + b; } }; class Plus { public : Plus ( int n = 10 ) :_n(n) {} static int plusi ( int a, int b) { return a + b; } double plusd ( double a, double b) { return (a + b) * _n; } private : int _n; }; int main () { // 包装各种可调⽤对象 function< int ( int , int )> f1 = f; function< int ( int , int )> f2 = Functor (); function< int ( int , int )> f3 = []( int a, int b) { return a + b; }; cout << f1 ( 1 , 1 ) << endl; cout << f2 ( 1 , 1 ) << endl; cout << f3 ( 1 , 1 ) << endl; // 包装静态成员函数 // 成员函数要指定类域并且前⾯加 & 才能获取地址 function< int ( int , int )> f4 = &Plus::plusi; cout << f4 ( 1 , 1 ) << endl; // 包装普通成员函数 // 普通成员函数还有⼀个隐含的 this 指针参数,所以绑定时传对象或者对象的指针过去都可以 function< double (Plus*, double , double )> f5 = &Plus::plusd; Plus pd; cout << f5 (&pd, 1.1 , 1.1 ) << endl; function< double (Plus, double , double )> f6 = &Plus::plusd; cout << f6 (pd, 1.1 , 1.1 ) << endl; cout << f6 (pd, 1.1 , 1.1 ) << endl; function< double (Plus&&, double , double )> f7 = &Plus::plusd; cout << f7 ( move (pd), 1.1 , 1.1 ) << endl; cout << f7 ( Plus (), 1.1 , 1.1 ) << endl; return 0 ; }

8.2bind

simple ( 1 ) 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 是⼀个函数模板,它也是⼀个可调⽤对象的包装器,可以把他看做⼀个函数适配器,对接收

的fn可调⽤对象进⾏处理后返回⼀个可调⽤对象。 bind 可以⽤来调整参数个数和参数顺序。

bind 也在<functional>这个头⽂件中。

调⽤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为第⼆个参数,以此类推。_1/_2/_3....这些占

位符放到placeholders的⼀个命名空间中。

# include <functional> using placeholders::_1; using placeholders::_2; using placeholders::_3; int Sub ( int a, int b) { return (a - b) * 10 ; } int SubX ( int a, int b, int c) { return (a - b - c) * 10 ; } class Plus { public : static int plusi ( int a, int b) { return a + b; } double plusd ( double a, double b) { return a + b; } }; int main () { auto sub1 = bind (Sub, _1, _2); cout << sub1 ( 10 , 5 ) << endl; // bind 本质返回的⼀个仿函数对象 // 调整参数顺序(不常⽤) // _1 代表第⼀个实参 // _2 代表第⼆个实参 // ... auto sub2 = bind (Sub, _2, _1); cout << sub2 ( 10 , 5 ) << endl; // 调整参数个数 (常⽤) auto sub3 = bind (Sub, 100 , _1); cout << sub3 ( 5 ) << endl; auto sub4 = bind (Sub, _1, 100 ); cout << sub4 ( 5 ) << endl; // 分别绑死第 123 个参数 auto sub5 = bind (SubX, 100 , _1, _2); cout << sub5 ( 5 , 1 ) << endl; auto sub6 = bind (SubX, _1, 100 , _2); cout << sub6 ( 5 , 1 ) << endl; auto sub7 = bind (SubX, _1, _2, 100 ); cout << sub7 ( 5 , 1 ) << endl; // 成员函数对象进⾏绑死,就不需要每次都传递了 function< double (Plus&&, double , double )> f6 = &Plus::plusd; Plus pd; cout << f6 ( move (pd), 1.1 , 1.1 ) << endl; cout << f6 ( Plus (), 1.1 , 1.1 ) << endl; // bind ⼀般⽤于,绑死⼀些固定参数 function< double ( double , double )> f7 = bind (&Plus::plusd, Plus (), _1, _2); cout << f7 ( 1.1 , 1.1 ) << endl; // 计算复利的 lambda auto func1 = []( double rate, double money, int year)-> double { double ret = money; for ( int i = 0 ; i < year; i++) { ret += ret * rate; } return ret - money; }; // 绑死⼀些参数,实现出⽀持不同年华利率,不同⾦额和不同年份计算出复利的结算利息 function< double ( double )> func3_1_5 = bind (func1, 0.015 , _1, 3 ); function< double ( double )> func5_1_5 = bind (func1, 0.015 , _1, 5 ); function< double ( double )> func10_2_5 = bind (func1, 0.025 , _1, 10 ); function< double ( double )> func20_3_5 = bind (func1, 0.035 , _1, 30 ); cout << func3_1_5 ( 1000000 ) << endl; cout << func5_1_5 ( 1000000 ) << endl; cout << func10_2_5 ( 1000000 ) << endl; cout << func20_3_5 ( 1000000 ) << endl; return 0 ; }

结束语 C++11总结完毕,智能指针部分下篇博客总结 OK,感谢观看!!!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.C++11的发展历史
  • 2.列表初始化
    • 2.1C++98传统的{}
    • 2.2C++11传统的{}
    • 2.3C++11中的std::initializer_list
  • 3.右值引用与移动语义
    • 3.1左值与右值
    • 3.2左值引用和右值引用
    • 3.3引用延长生命周期
    • 3.4左值和右值的参数匹配
    • 3.5右值引用和移动语义的使用场景
      • 3.5.1左值引用主要使用场景回顾
      • 3.5.2移动构造和移动赋值
      • 3.5.3右值引用和移动语义解决传值返回问题
    • 3.6类型分类
    • 3.7引用折叠
    • 3.8完美转发
  • 4.可变模版参数
    • 4.1基本语法及原理
    • 4.2包扩展
    • 4.3empalce系列接口
  • 5.新的类功能
    • 5.1默认的移动构造和移动赋值
    • 5.2defult和delete
  • 6.STL中⼀些变化
  • 7.lambda
    • 7.1lambda表达式语法
    • 7.2捕捉列表
    • 7.3lambda的应用
    • 7.4lambda的原理
  • 8.包装器
    • 8.1function
    • 8.2bind
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档