< C++11新特性(部分学习)>——《C++高阶》

目录

1.C++11简介:

2. 统一的列表初始化

2.1 {}初始化

 2.2 std::initializer_list

3. 声明

3.1 auto

3.2 decltype

3.3 nullptr

4. 范围for循环

5. 智能指针

6. STL中一些变化

7 .右值引用和移动语义

7.1 左值引用和右值引用

7.2 左值引用与右值引用比较

7.3 右值引用使用场景和意义

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

7.5 完美转发

9. 可变参数模板

后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                           ——By 作者:新晓·故知


1.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++11 

小故事:

1998年是C++标准委员会成立的第一年,本来计划以后每5年视实际需要更新一次标准,C++国际 标准委员会在研究C++ 03的下一个版本的时候,一开始计划是2007年发布,所以最初这个标准叫 C++ 07。但是到06年的时候,官方觉得2007年肯定完不成C++ 07,而且官方觉得2008年可能也 完不成。最后干脆叫C++ 0x。x的意思是不知道到底能在07还是08还是09年完成。结果2010年的 时候也没完成,最后在2011年终于完成了C++标准。所以最终定名为C++11。

2. 统一的列表初始化

2.1 {}初始化

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

 
 
  1. struct Point

  2. {

  3. int _x;

  4. int _y;

  5. };

  6. int main()

  7. {

  8. int array1[] = { 1, 2, 3, 4, 5 };

  9. int array2[5] = { 0 };

  10. Point p = { 1, 2 };

  11. return 0;

  12. }

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

 
 
  1. int main()

  2. {

  3. //列表初始化(注意:不同于初始化列表!)

  4. int x1 = 1; //一般初始化

  5. int x2 = { 2 }; //{}初始化一切

  6. int x3{ 3 }; //{}初始化

  7. cout << "x1=" << x1 << endl;

  8. cout << "x2=" << x2 << endl;

  9. cout << "x3=" << x3 << endl;

  10. return 0;

  11. }

 
 
  1. struct Point

  2. {

  3. int _x;

  4. int _y;

  5. };

  6. int main()

  7. {

  8. int x1 = 1;

  9. int x2{ 2 };

  10. int array1[]{ 1, 2, 3, 4, 5 };

  11. int array2[5]{ 0 };

  12. Point p{ 1, 2 };

  13. // C++11中列表初始化也可以适用于new表达式中

  14. int* pa = new int[4]{ 0 };

  15. return 0;

  16. }

 
 
  1. struct Point

  2. {

  3. int _x;

  4. int _y;

  5. };

  6. int main()

  7. {

  8. //列表初始化(注意:不同于初始化列表!)

  9. //去掉赋值号初始化

  10. int arr1[]{ 1,2,3,4 };

  11. int arr2[5]{ 0 };

  12. Point p{ 1,2 };

  13. int* p1 = new int(1);

  14. int* p2 = new int[3]{ 1,3,4 };

  15. return 0;

  16. }

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

 
 
 
  1. class Date

  2. {

  3. public:

  4. Date(int year, int month, int day)

  5. :_year(year)

  6. , _month(month)

  7. , _day(day)

  8. {

  9. cout << "Date(int year, int month, int day)" << endl;

  10. }

  11. private:

  12. int _year;

  13. int _month;

  14. int _day;

  15. };

  16. int main()

  17. {

  18. Date d1(2022, 1, 1); // old style

  19. // C++11支持的列表初始化,这里会调用构造函数初始化

  20. Date d2{ 2022, 1, 2 };

  21. Date d3 = { 2022, 1, 3 };

  22. return 0;

  23. }

 
 
  1. class Date

  2. {

  3. public:

  4. Date(int year, int month, int day)

  5. :_year(year)

  6. , _month(month)

  7. , _day(day)

  8. {

  9. cout << "Date(int year, int month, int day)" << endl;

  10. }

  11. private:

  12. int _year;

  13. int _month;

  14. int _day;

  15. };

  16. int main()

  17. {

  18. Date d1(2022, 1, 1); // 一般方式

  19. // C++11支持的列表初始化,这里会调用构造函数初始化

  20. Date d2{ 2022, 1, 2 };

  21. Date d3 = { 2022, 1, 3 };

  22. Date* p4 = new Date(2022, 9, 18);

  23. Date* p5 = new Date[3]{ {2022, 9, 18},{2022,9,19},{2022,9,19} };

  24. return 0;

  25. }

说明:

尽管有些新特性看起来“别扭”,但那是为了其他而作铺垫(可以不使用,但要认识这种用法),语言怎么用起来顺手得看个人。上面的新特性,在某一方面是为了更好的支持new[ ]的初始化问题。

 2.2 std::initializer_list

std::initializer_list的介绍文档:https://cplusplus.com/reference/initializer_list/initializer_list/

 
 
  1. int main()

  2. {

  3. // the type of il is an initializer_list

  4. auto il = { 10, 20, 30 };

  5. cout << typeid(il).name() << endl;

  6. return 0;

  7. }

std::initializer_list使用场景:

std::initializer_list一般是作为构造函数的参数,C++11对STL中的不少容器就增加

std::initializer_list作为参数的构造函数,这样初始化容器对象就更方便了。也可以作为operator= 的参数,这样就可以用大括号赋值。

链接:

https://cplusplus.com/reference/list/list/list/

https://cplusplus.com/reference/vector/vector/vector/

https://cplusplus.com/reference/map/map/map/

https://cplusplus.com/reference/vector/vector/operator=/

 
 
  1. int main()

  2. {

  3. vector<int> v = { 1,2,3,4 };

  4. list<int> lt = { 1,2 };

  5. // 这里{"sort", "排序"}会先初始化构造一个pair对象

  6. map<string, string> dict = { {"sort", "排序"}, {"insert", "插入"} };

  7. // 使用大括号对容器赋值

  8. v = {10, 20, 30};

  9. return 0;

  10. }

让模拟实现的vector也支持{}初始化和赋值:
 
 
  1. //模拟实现的vector使其支持{}初始化

  2. namespace my

  3. {

  4. template<class T>

  5. class vector

  6. {

  7. public:

  8. typedef T* iterator;

  9. vector(initializer_list<T> l)

  10. {

  11. _start = new T[l.size()];

  12. _finish = _start + l.size();

  13. _endofstorage = _start + l.size();

  14. iterator vit = _start;

  15. typename initializer_list<T>::iterator lit = l.begin();

  16. //迭代器遍历

  17. /*while (lit != l.end())

  18. {

  19. *vit++ = *lit++;

  20. }*/

  21. //范围for遍历

  22. for (auto e : l)

  23. {

  24. cout << e << " ";

  25. }

  26. cout << endl;

  27. }

  28. vector<T>& operator=(initializer_list<T> l)

  29. {

  30. vector<T> tmp(l);

  31. std::swap(_start, tmp._start);

  32. std::swap(_finish, tmp._finish);

  33. std::swap(_endofstorage, tmp._endofstorage);

  34. return *this;

  35. }

  36. private:

  37. iterator _start;

  38. iterator _finish;

  39. iterator _endofstorage;

  40. };

  41. }

注意:vector等容器支持与Date类支持的原理不同!

例如Date类A:

{}初始化演示:

 
 
  1. //4.容器的列表初始化

  2. class Date

  3. {

  4. public:

  5. Date(int year, int month, int day)

  6. :_year(year)

  7. , _month(month)

  8. , _day(day)

  9. {

  10. cout << "Date(int year, int month, int day)" << endl;

  11. }

  12. private:

  13. int _year;

  14. int _month;

  15. int _day;

  16. };

  17. int main()

  18. {

  19. //一般初始化

  20. vector<int> v1 (9);

  21. vector<int> v2(9,9);

  22. // C++11支持的列表初始化(容器初始化)

  23. vector<int> v3 = { 1,2,3,4,5 };

  24. vector<int> v4{ 6,7,8,9,10 };

  25. vector<Date> v5{ {2022, 9, 18},{2022,9,19},{2022,9,19} };

  26. return 0;

  27. }

 

 
 
  1. //其他容器的列表初始化

  2. int main()

  3. {

  4. list<int> lt1(3);

  5. list<int> lt2(3,2);

  6. list<int> lt3{ 1,2,3 };

  7. set<int> st1;

  8. set<int> st2{ 4,5,6 };

  9. map<string, string> dict = { {"排序","sort"},{"左边","left"},{"剩余","left"} };

  10. return 0;

  11. }

 容器的列表初始胡支持原理:C++11创建了一个新类型:

3. 声明

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

3.1 auto

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

 
 
  1. int main()

  2. {

  3. int i = 10;

  4. auto p = &i;

  5. auto pf = strcpy;

  6. cout << typeid(p).name() << endl;

  7. cout << typeid(pf).name() << endl;

  8. map<string, string> dict = { {"sort", "排序"}, {"insert", "插入"} };

  9. //map<string, string>::iterator it = dict.begin();

  10. auto it = dict.begin();

  11. return 0;

  12. }

3.2 decltype

关键字decltype将变量的类型声明为表达式指定的类型。
 
 
  1. // decltype的一些使用使用场景

  2. template<class T1, class T2>

  3. void F(T1 t1, T2 t2)

  4. {

  5. decltype(t1 * t2) ret;

  6. cout << typeid(ret).name() << endl;

  7. }

  8. int main()

  9. {

  10. const int x = 1;

  11. double y = 2.2;

  12. decltype(x * y) ret; // ret的类型是double

  13. decltype(&x) p; // p的类型是int*

  14. cout << typeid(ret).name() << endl;

  15. cout << typeid(p).name() << endl; F(1, 'a');

  16. return 0;

  17. }

3.3 nullptr

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

 
 
  1. #ifndef NULL

  2. #ifdef __cplusplus

  3. #define NULL   0

  4. #else

  5. #define NULL   ((void *)0)

  6. #endif

  7. #endif

4. 范围for循环

这里在前面章节已学习,深入学习参见官方文档。

用法举例:

5. 智能指针

这个部分后期会进行专门学习。

6. STL中一些变化

新容器

用橘色圈起来是C++11中的一些几个新容器,但是实际最有用的是unordered_map和

unordered_set。

容器中的一些新方法

如果我们再细细去看会发现基本每个容器中都增加了一些C++11的方法,但是其实很多都是用得 比较少的。

比如提供了cbegin和cend方法返回const迭代器等等,但是实际意义不大,因为begin和end也是 可以返回const迭代器的,这些都是属于锦上添花的操作。

实际上C++11更新后,容器中增加的新方法最后用的插入接口函数的右值引用版本:

https://cplusplus.com/reference/vector/vector/emplace_back/

https://cplusplus.com/reference/map/map/emplace/

https://cplusplus.com/reference/map/map/insert/ 

https://cplusplus.com/reference/vector/vector/push_back/ 

但是这些接口到底意义在哪?网上都说他们能提高效率,他们是如何提高效率的?

请看下面的右值引用和移动语义章节的讲解。另外emplace还涉及模板的可变参数,也需要再继续深入学习后面章节的知识。

7 .右值引用和移动语义

7.1 左值引用和右值引用

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

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

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

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

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

需要注意的是右值是不能取地址的,但是给右值取别名后,会导致右值被存储到特定位置,且可以取到该位置的地址,也就是说例如:不能取字面量10的地址,但是rr1引用后,可以对rr1取地址,也可以修改rr1。如果不想rr1被修改,可以用const int&& rr1 去引用,是不是感觉很神奇, 这个了解一下实际中右值引用的使用场景并不在于此,这个特性也不重要。

 测试示例:

7.2 左值引用与右值引用比较

左值引用总结:

1. 左值引用只能引用左值,不能引用右值。

2. 但是const左值引用既可引用左值,也可引用右值

 

右值引用总结:

1. 右值引用只能右值,不能引用左值。

2. 但是右值引用可以move以后的左值。

7.3 右值引用使用场景和意义

前面我们可以看到左值引用既可以引用左值和又可以引用右值,那为什么C++11还要提出右值引用呢?是不是化蛇添足呢?下面我们来看看左值引用的短板,右值引用是如何补齐这个短板的!

下面场景遇到的问题,只能传值返回,使用左值引用解决不了:

右值分类:

1.纯右值

2.将亡值

 move可以将一个左值属性的元素A转为具有右值属性的元素A",这就使得当别人引用被转后A"时,也可以“掠夺”被引用元素A"的资源。

 深拷贝的问题:

 传值返回+深拷贝:

编译器优化: 既有拷贝构造也有移动构造:

编译器优化:

深拷贝:左值拷贝是不会被资源转移

右值拷贝:会转移将亡值的资源,但提升了效率! 

 STL容器的移动构造:

值的肯定的是:C++11以后,STL的容器,都只吃了移动构造和移动赋值!这大大提升了开发效率!

例如: 

 

 移动赋值:

 
 
  1. namespace my

  2. {

  3. class string

  4. {

  5. public:

  6. typedef char* iterator;

  7. iterator begin()

  8. {

  9. return _str;

  10. }

  11. iterator end()

  12. {

  13. return _str + _size;

  14. }

  15. string(const char* str = "")

  16. :_size(strlen(str))

  17. , _capacity(_size)

  18. {

  19. //cout << "string(char* str)" << endl;

  20. _str = new char[_capacity + 1];

  21. strcpy(_str, str);

  22. }

  23. // s1.swap(s2)

  24. void swap(string& s)

  25. {

  26. ::swap(_str, s._str);

  27. ::swap(_size, s._size);

  28. ::swap(_capacity, s._capacity);

  29. }

  30. // 拷贝构造

  31. string(const string& s)

  32. :_str(nullptr)

  33. {

  34. cout << "string(const string& s) -- 深拷贝" << endl;

  35. string tmp(s._str);

  36. swap(tmp);

  37. }

  38. // 赋值重载

  39. string& operator=(const string& s)

  40. {

  41. cout << "string& operator=(string s) -- 深拷贝" << endl;

  42. string tmp(s);

  43. swap(tmp);

  44. return *this;

  45. }

  46. // 移动构造

  47. string(string && s)

  48. :_str(nullptr)

  49. , _size(0)

  50. , _capacity(0)

  51. {

  52. cout << "string(string&& s) -- 移动语义" << endl;

  53. swap(s);

  54. }

  55. // 移动赋值

  56. string& operator=(string && s)

  57. {

  58. cout << "string& operator=(string&& s) -- 移动语义" << endl;

  59. swap(s);

  60. return *this;

  61. }

  62. ~string()

  63. {

  64. delete[] _str;

  65. _str = nullptr;

  66. }

  67. char& operator[](size_t pos)

  68. {

  69. assert(pos < _size);

  70. return _str[pos];

  71. }

  72. void reserve(size_t n)

  73. {

  74. if (n > _capacity)

  75. {

  76. char* tmp = new char[n + 1];

  77. strcpy(tmp, _str);

  78. delete[] _str;

  79. _str = tmp;

  80. _capacity = n;

  81. }

  82. }

  83. void push_back(char ch)

  84. {

  85. if (_size >= _capacity)

  86. {

  87. size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;

  88. reserve(newcapacity);

  89. }

  90. _str[_size] = ch;

  91. ++_size;

  92. _str[_size] = '\0';

  93. }

  94. //string operator+=(char ch)

  95. string& operator+=(char ch)

  96. {

  97. push_back(ch);

  98. return *this;

  99. }

  100. const char* c_str() const

  101. {

  102. return _str;

  103. }

  104. private:

  105. char* _str;

  106. size_t _size;

  107. size_t _capacity; // 不包含最后做标识的\0

  108. };

  109. }

左值引用的使用场景:

做参数和做返回值都可以提高效率。
 
 
  1. void func1(my::string s)

  2. {}

  3. void func2(const my::string& s)

  4. {}

  5. int main()

  6. {

  7. my::string s1("hello world");

  8. // func1和func2的调用我们可以看到左值引用做参数减少了拷贝,提高效率的使用场景和价值

  9. func1(s1);

  10. func2(s1);

  11. // string operator+=(char ch) 传值返回存在深拷贝

  12. // string& operator+=(char ch) 传左值引用没有拷贝提高了效率

  13. s1 += '!';

  14. return 0;

  15. }

左值引用的短板:

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

 
 
  1. //模拟实现的string类

  2. namespace my

  3. {

  4. class string

  5. {

  6. public:

  7. typedef char* iterator;

  8. iterator begin()

  9. {

  10. return _str;

  11. }

  12. iterator end()

  13. {

  14. return _str + _size;

  15. }

  16. string(const char* str = "")

  17. :_size(strlen(str))

  18. , _capacity(_size)

  19. {

  20. //cout << "string(char* str)" << endl;

  21. _str = new char[_capacity + 1];

  22. strcpy(_str, str);

  23. }

  24. // s1.swap(s2)

  25. void swap(string& s)

  26. {

  27. ::swap(_str, s._str);

  28. ::swap(_size, s._size);

  29. ::swap(_capacity, s._capacity);

  30. }

  31. // 拷贝构造

  32. string(const string& s)

  33. :_str(nullptr)

  34. {

  35. cout << "string(const string& s) -- 深拷贝" << endl;

  36. string tmp(s._str);

  37. swap(tmp);

  38. }

  39. // 赋值重载

  40. string& operator=(const string& s)

  41. {

  42. cout << "string& operator=(string s) -- 深拷贝" << endl;

  43. string tmp(s);

  44. swap(tmp);

  45. return *this;

  46. }

  47. // 移动构造

  48. string(string&& s)

  49. :_str(nullptr)

  50. , _size(0)

  51. , _capacity(0)

  52. {

  53. cout << "string(string&& s) -- 移动语义" << endl;

  54. swap(s);

  55. }

  56. // 移动赋值

  57. string& operator=(string&& s)

  58. {

  59. cout << "string& operator=(string&& s) -- 移动语义" << endl;

  60. swap(s);

  61. return *this;

  62. }

  63. ~string()

  64. {

  65. delete[] _str;

  66. _str = nullptr;

  67. }

  68. char& operator[](size_t pos)

  69. {

  70. assert(pos < _size);

  71. return _str[pos];

  72. }

  73. void reserve(size_t n)

  74. {

  75. if (n > _capacity)

  76. {

  77. char* tmp = new char[n + 1];

  78. strcpy(tmp, _str);

  79. delete[] _str;

  80. _str = tmp;

  81. _capacity = n;

  82. }

  83. }

  84. void push_back(char ch)

  85. {

  86. if (_size >= _capacity)

  87. {

  88. size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;

  89. reserve(newcapacity);

  90. }

  91. _str[_size] = ch;

  92. ++_size;

  93. _str[_size] = '\0';

  94. }

  95. //string operator+=(char ch)

  96. string& operator+=(char ch)

  97. {

  98. push_back(ch);

  99. return *this;

  100. }

  101. const char* c_str() const

  102. {

  103. return _str;

  104. }

  105. private:

  106. char* _str;

  107. size_t _size;

  108. size_t _capacity; // 不包含最后做标识的\0

  109. };

  110. }

  111. //模拟实现to_string(附用my::string)

  112. namespace my

  113. {

  114. my::string to_string(int value)

  115. {

  116. bool flag = true;

  117. if (value < 0)

  118. {

  119. flag = false;

  120. value = 0 - value;

  121. }

  122. my::string str;

  123. while (value > 0)

  124. {

  125. int x = value % 10;

  126. value /= 10;

  127. str += ('0' + x);

  128. }

  129. if (flag == false)

  130. {

  131. str += '-';

  132. }

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

  134. return str;

  135. }

  136. }

  137. int main()

  138. {

  139. // 在bit::string to_string(int value)函数中可以看到,这里

  140. // 只能使用传值返回,传值返回会导致至少1次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)。

  141. my::string ret1 = my::to_string(1234);

  142. my::string ret2 = my::to_string(-1234);

  143. return 0;

  144. }

 

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

在bit::string中增加移动构造,移动构造本质是将参数右值的资源窃取过来,占位已有,那么就不用做深拷贝了,所以它叫做移动构造,就是窃取别人的资源来构造自己

再运行上面bit::to_string的两个调用,我们会发现,这里没有调用深拷贝的拷贝构造,而是调用 了移动构造,移动构造中没有新开空间,拷贝数据,所以效率提高了。

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

在bit::string类中增加移动赋值函数,再去调用bit::to_string(1234),不过这次是将

bit::to_string(1234)返回的右值对象赋值给ret1对象,这时调用的是移动构造。

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

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

https://cplusplus.com/reference/string/string/string/

https://cplusplus.com/reference/vector/vector/vector/

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

按照语法,右值引用只能引用右值,但右值引用一定不能引用左值吗?因为:有些场景下,可能 真的需要用右值去引用左值实现移动语义。当需要用右值引用引用一个左值时,可以通过move 函数将左值转化为右值。C++11中,std::move()函数位于 头文件中,该函数名字具有迷惑性, 它并不搬移任何东西,唯一的功能就是将一个左值强制转化为右值引用,然后实现移动语义

 总结:

左值引用的深拷贝---->拷贝构造/拷贝赋值

右值引用的深拷贝---->移动构造/移动赋值

1.深拷贝对象,传值返回,调用移动构造,那么效率就提高了。

STL容器插入接口函数也增加了右值引用版本:

https://cplusplus.com/reference/vector/vector/push_back/

https://cplusplus.com/reference/list/list/push_back/https://cplusplus.com/reference/list/list/push_back/

要注意,这里的可打印出“深拷贝、资源转移等”是调用自己模拟实现的STL,若调用库里的无法查看。

右值引用使得移动构造和移动赋值,实现了资源转移,提升了效率。如果不支持右值引用,那么左值引用进行深拷贝既要创建,又要销毁,降低了效率。但是要注意右值引用的移动操作的使用。右值引用解决了传值返回的一些问题。

7.5 完美转发

 模板中的&& 万能引用  

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

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

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

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

  5. // 模板中的&&不代表右值引用,而是万能引用,其既能接收左值又能接收右值。

  6. // 模板的万能引用只是提供了能够接收同时接收左值引用和右值引用的能力,

  7. // 但是引用类型的唯一作用就是限制了接收的类型,后续使用中都退化成了左值,

  8. // 我们希望能够在传递过程中保持它的左值或者右值的属性, 就需要用我们下面学习的完美转发

  9. template<typename T>

  10. void PerfectForward(T&& t)

  11. {

  12. Fun(t);

  13. }

  14. int main()

  15. {

  16. PerfectForward(10); // 右值

  17. int a;

  18. PerfectForward(a); // 左值

  19. PerfectForward(std::move(a)); // 右值

  20. const int b = 8;

  21. PerfectForward(b); // const 左值

  22. PerfectForward(std::move(b)); // const 右值

  23. return 0;

  24. }

这里右值引用的接收对象是左值属性的,可以取地址。 

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

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

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

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

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

  5. // std::forward<T>(t)在传参的过程中保持了t的原生类型属性。

  6. template<typename T>

  7. void PerfectForward(T&& t) {

  8. Fun(std::forward<T>(t));

  9. }

  10. int main()

  11. {

  12. PerfectForward(10); // 右值

  13. int a;

  14. PerfectForward(a); // 左值

  15. PerfectForward(std::move(a)); // 右值

  16. const int b = 8;

  17. PerfectForward(b); // const 左值

  18. PerfectForward(std::move(b)); // const 右值

  19. return 0;

  20. }

 完美转发实际中的使用场景:

8. 新的类功能

默认成员函数

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

1. 构造函数

2. 析构函数

3. 拷贝构造函数

4. 拷贝赋值重载

5. 取地址重载

6. const 取地址重载

最后重要的是前4个,后两个用处不大。默认成员函数就是我们不写编译器会生成一个默认的。

C++11 新增了两个:移动构造函数和移动赋值运算符重载。

针对移动构造函数和移动赋值运算符重载有一些需要注意的点如下:
 
 
  1. // 以下代码在vs2013中不能体现,在vs2019下才能演示体现上面的特性。

  2. class Person

  3. {

  4. public:

  5. Person(const char* name = "", int age = 0)

  6. :_name(name)

  7. , _age(age)

  8. {}

  9. /*Person(const Person& p)

  10. * :_name(p._name)

  11. ,_age(p._age)

  12. {}*/

  13. /*Person& operator=(const Person& p)

  14. {

  15. if(this != &p)

  16. {

  17. _name = p._name;

  18. _age = p._age;

  19. }

  20. return *this;

  21. }*/

  22. /*~Person()

  23. {}*/

  24. private:

  25. my::string _name;

  26. int _age;

  27. };

  28. int main()

  29. {

  30. Person s1;

  31. Person s2 = s1;

  32. Person s3 = std::move(s1);

  33. Person s4;

  34. s4 = std::move(s2);

  35. return 0;

  36. }

类成员变量初始化

C++11允许在类定义时给成员变量初始缺省值,默认生成构造函数会使用这些缺省值初始化,这个我们在雷和对象默认就讲了,这里就不再细讲了。

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

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

 
 
  1. class Person

  2. {

  3. public:

  4. Person(const char* name = "", int age = 0)

  5. :_name(name)

  6. , _age(age)

  7. {}

  8. Person(const Person& p)

  9. :_name(p._name)

  10. , _age(p._age)

  11. {}

  12. Person(Person&& p) = default;

  13. private:

  14. my::string _name;

  15. int _age;

  16. };

  17. int main()

  18. {

  19. Person s1;

  20. Person s2 = s1;

  21. Person s3 = std::move(s1);

  22. return 0;

  23. }

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

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

 
 
  1. class Person

  2. {

  3. public:

  4. Person(const char* name = "", int age = 0)

  5. :_name(name)

  6. , _age(age)

  7. {}

  8. Person(const Person& p) = delete;

  9. private:

  10. my::string _name;

  11. int _age;

  12. };

  13. int main()

  14. {

  15. Person s1;

  16. Person s2 = s1;

  17. Person s3 = std::move(s1);

  18. return 0;

  19. }

继承和多态中的fifinal与override关键字

这个在之前的学习中已涉及,深入学习可参见官方文档。      

9. 可变参数模板

C++11的新特性可变参数模板能够让您创建可以接受可变参数的函数模板和类模板,相比

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

下面就是一个基本可变参数的函数模板:
 
 
  1. // Args是一个模板参数包,args是一个函数形参参数包

  2. // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。

  3. template <class ...Args>

  4. void ShowList(Args... args)

  5. {}

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

 
 
  1. // Args是一个模板参数包,args是一个函数形参参数包

  2. // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。

  3. template <class ...Args>

  4. void ShowList(Args... args)

  5. {

  6. cout << sizeof...(args) << endl;

  7. }

  8. int main()

  9. {

  10. ShowList(1, 'x', 1.1);

  11. ShowList(1, 2, 3, 4, 5);

  12. return 0;

  13. }

递归函数方式展开参数包

 

 
 
  1. // Args是一个模板参数包,args是一个函数形参参数包

  2. // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。

  3. template <class T>

  4. void ShowList(const T& val)

  5. {

  6. cout << val <<"类型:" << typeid(val).name() << endl;

  7. }

  8. template <class T,class ...Args>

  9. void ShowList(const T& val,Args... args)

  10. {

  11. //参数个数

  12. cout <<"参数个数:" << sizeof...(args) << endl;

  13. cout << val << "类型:" << typeid(val).name() << endl;

  14. ShowList(args...);

  15. }

  16. int main()

  17. {

  18. ShowList(1, 'x', 1.1);

  19. ShowList(1, 2, 3, 4, 5);

  20. return 0;

  21. }

 

 
 
  1. // Args是一个模板参数包,args是一个函数形参参数包

  2. // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。

  3. template <class T>

  4. void ShowList(const T& val)

  5. {

  6. cout << val << "->" << typeid(val).name() << endl;

  7. }

  8. template <class T,class ...Args>

  9. void ShowList(const T& val,Args... args)

  10. {

  11. //参数个数

  12. cout << sizeof...(args) << endl;

  13. cout << val <<"->" << typeid(val).name() << endl;

  14. ShowList(args...);

  15. }

  16. int main()

  17. {

  18. ShowList(1, 'x', 1.1);

  19. //ShowList(1, 2, 3, 4, 5);

  20. return 0;

  21. }

 

 
 
  1. // Args是一个模板参数包,args是一个函数形参参数包

  2. // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。

  3. void ShowList()

  4. {}

  5. template <class T, class ...Args>

  6. void ShowList(const T& val, Args... args)

  7. {

  8. //参数个数

  9. cout << sizeof...(args) << endl;

  10. cout << val << "->" << typeid(val).name() << endl;

  11. ShowList(args...);

  12. }

  13. int main()

  14. {

  15. ShowList(1, 'x', 1.1);

  16. //ShowList(1, 2, 3, 4, 5);

  17. return 0;

  18. }

 

逗号表达式展开参数包

这种展开参数包的方式,不需要通过递归终止函数,是直接在expand函数体中展开的, printarg不是一个递归终止函数,只是一个处理参数包中每一个参数的函数。这种就地展开参数包的方式实现的关键是逗号表达式。我们知道逗号表达式会按顺序执行逗号前面的表达式。

expand函数中的逗号表达式:(printarg(args), 0),也是按照这个执行顺序,先执行

printarg(args),再得到逗号表达式的结果0。同时还用到了C++11的另外一个特性——初始化列表,通过初始化列表来初始化一个变长数组, {(printarg(args), 0)...}将会展开成((printarg(arg1),0),(printarg(arg2),0), (printarg(arg3),0), etc... ),最终会创建一个元素值都为0的数组int arr[sizeof...(Args)]。由于是逗号表达式,在创建数组的过程中会先执行逗号表达式前面的部分printarg(args) 打印出参数,也就是说在构造int数组的过程中就将参数包展开了,这个数组的目的纯粹是为了在 数组构造的过程展开参数包

 
 
  1. template <class T>

  2. void PrintArg(T t)

  3. {

  4. cout << t << " ";

  5. }

  6. //展开函数

  7. template <class ...Args>

  8. void ShowList(Args... args)

  9. {

  10. int arr[] = { (PrintArg(args), 0)... };

  11. cout << endl;

  12. }

  13. int main()

  14. {

  15. ShowList(1);

  16. ShowList(1, 'A');

  17. ShowList(1, 'A', std::string("sort"));

  18. return 0;

  19. }

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

https://cplusplus.com/reference/vector/vector/emplace_back/

https://cplusplus.com/reference/list/list/emplace_back/

 
 
  1. template <class... Args>

  2. void emplace_back (Args&&... args);

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

 
 
  1. int main()

  2. {

  3. std::list< std::pair<int, char> > mylist;

  4. // emplace_back支持可变参数,拿到构建pair对象的参数后自己去创建对象

  5. // 那么在这里我们可以看到除了用法上,和push_back没什么太大的区别

  6. mylist.emplace_back(10, 'a');

  7. mylist.emplace_back(20, 'b');

  8. mylist.emplace_back(make_pair(30, 'c'));

  9. mylist.push_back(make_pair(40, 'd'));

  10. mylist.push_back({ 50, 'e' });

  11. for (auto e : mylist)

  12. cout << e.first << ":" << e.second << endl;

  13. return 0;

  14. }

 

 
 
  1. int main()

  2. {

  3. // 下面我们试一下带有拷贝构造和移动构造的bit::string,再试试呢

  4. // 我们会发现其实差别也不到,emplace_back是直接构造了,push_back

  5. // 是先构造,再移动构造,其实也还好。

  6. std::list< std::pair<int, my::string> > mylist;

  7. mylist.emplace_back(10, "sort");

  8. mylist.emplace_back(make_pair(20, "sort"));

  9. mylist.push_back(make_pair(30, "sort"));

  10. mylist.push_back({ 40, "sort" });

  11. return 0;

  12. }

后记:
●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                           ——By 作者:新晓·故知

(1646条消息) < C++11新特性(部分学习)>——《C++高阶》_新晓·故知(考研停更)的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值