• 【C++航海王:追寻罗杰的编程之路】C++11(二)


    目录

    C++11(上)

    1 -> STL中的一些变化

    2 -> 右值引用和移动语义

    2.1 -> 左值引用和右值引用

    2.2 -> 左值引用与右值引用比较

    2.3 -> 右值引用使用场景与意义

     2.4 -> 右值引用引用左值及其更深入的使用场景分析

    2.5 -> 完美转发


    C++11(上)

    1 -> STL中的一些变化

    新容器

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

    容器中的一些新方法

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

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

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

    std::vector::emplace_back

    std::vector::push_back

    std::map::insert

    std::map::emplace

    2 -> 右值引用和移动语义

    2.1 -> 左值引用和右值引用

    传统的C++语法中就有引用的语法,而C++11中新增的右值引用语法特性。无论左值引用还是右值引用,都是给对象取别名。

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

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

    1. #define _CRT_SECURE_NO_WARNINGS 1
    2. #include <iostream>
    3. using namespace std;
    4. int main()
    5. {
    6. // 以下的p、b、c、*p都是左值
    7. int* p = new int(0);
    8. int b = 1;
    9. const int c = 2;
    10. // 以下几个是对上面左值的左值引用
    11. int*& rp = p;
    12. int& rb = b;
    13. const int& rc = c;
    14. int& pvalue = *p;
    15. return 0;
    16. }

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

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

    1. #define _CRT_SECURE_NO_WARNINGS 1
    2. #include <iostream>
    3. using namespace std;
    4. int main()
    5. {
    6. double x = 1.1;
    7. double y = 2.2;
    8. // 以下几个都是常见的右值
    9. //10;
    10. //x + y;
    11. //fmin(x, y);
    12. // 以下几个都是对右值的右值引用
    13. int&& rr1 = 10;
    14. double&& rr2 = x + y;
    15. double&& rr3 = fmin(x, y);
    16. // 这里编译会报错:error C2106: “=”: 左操作数必须为左值
    17. //10 = 1;
    18. //x + y = 1;
    19. //fmin(x, y) = 1;
    20. return 0;
    21. }

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

    1. #define _CRT_SECURE_NO_WARNINGS 1
    2. #include <iostream>
    3. using namespace std;
    4. int main()
    5. {
    6. double x = 1.1;
    7. double y = 2.2;
    8. int&& rr1 = 10;
    9. const double&& rr2 = x + y;
    10. rr1 = 20;
    11. // 报错
    12. rr2 = 5.5;
    13. return 0;
    14. }

    2.2 -> 左值引用与右值引用比较

    左值引用总结:

    1. 左值引用只能引用左值,不能引用右值。
    2. const左值引用既可引用左值,也可引用右值。
    1. #define _CRT_SECURE_NO_WARNINGS 1
    2. #include <iostream>
    3. using namespace std;
    4. int main()
    5. {
    6. // 左值引用只能引用左值,不能引用右值。
    7. int a = 10;
    8. int& ra1 = a; // ra为a的别名
    9. //int& ra2 = 10;   // 编译失败,因为10是右值
    10. // const左值引用既可引用左值,也可引用右值。
    11. const int& ra3 = 10;
    12. const int& ra4 = a;
    13. return 0;
    14. }

    右值引用总结:

    1. 右值引用只能引用右值,不能引用左值。
    2. 右值引用可以move以后的左值。
    1. #define _CRT_SECURE_NO_WARNINGS 1
    2. #include <iostream>
    3. using namespace std;
    4. int main()
    5. {
    6. // 右值引用只能右值,不能引用左值。
    7. int&& r1 = 10;
    8. // error C2440: “初始化”: 无法从“int”转换为“int &&
    9. // message : 无法将左值绑定到右值引用
    10. int a = 10;
    11. int&& r2 = a;
    12. // 右值引用可以引用move以后的左值
    13. int&& r3 = std::move(a);
    14. return 0;
    15. }

    2.3 -> 右值引用使用场景与意义

    之前也有看到左值引用既可以引用左值也可以引用右值,那么C++11为什么还要提出右值引用呢?是不是在画蛇添足呢?下面来看看左值引用的短板,右值引用又是如何补齐短板的

    1. namespace fyd
    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(fyd::string s)
    2. {}
    3. void func2(const fyd::string& s)
    4. {}
    5. int main()
    6. {
    7. fyd::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. }

    左值引用的短板:

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

    1. namespace fyd
    2. {
    3. fyd::string to_string(int value)
    4. {
    5. bool flag = true;
    6. if (value < 0)
    7. {
    8. flag = false;
    9. value = 0 - value;
    10. }
    11. fyd::string str;
    12. while (value > 0)
    13. {
    14. int x = value % 10;
    15. value /= 10;
    16. str += ('0' + x);
    17. }
    18. if (flag == false)
    19. {
    20. str += '-';
    21. }
    22. std::reverse(str.begin(), str.end());
    23. return str;
    24. }
    25. }
    26. int main()
    27. {
    28. // 在fyd::string to_string(int value)函数中可以看到,这里
    29. // 只能使用传值返回,传值返回会导致至少1次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)。
    30. fyd::string ret1 = fyd::to_string(1234);
    31. fyd::string ret2 = fyd::to_string(-1234);
    32. return 0;
    33. }

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

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

    1. // 移动构造
    2. string(string&& s)
    3. :_str(nullptr)
    4. , _size(0)
    5. , _capacity(0)
    6. {
    7. cout << "string(string&& s) -- 移动语义" << endl;
    8. swap(s);
    9. }
    10. int main()
    11. {
    12. fyd::string ret2 = fyd::to_string(-1234);
    13. return 0;
    14. }

    移动构造中没有新开空间,拷贝数据,所以提高了效率。

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

    在fyd::string类中增加移动赋值函数,再去调用bit::to_string(1234),不过这次是将
    fyd::to_string(1234)返回的右值对象赋值给ret1对象,这时调用的是移动构造。

    1. // 移动赋值
    2. string& operator=(string&& s)
    3. {
    4. cout << "string& operator=(string&& s) -- 移动语义" << endl;
    5. swap(s);
    6. return *this;
    7. }
    8. int main()
    9. {
    10. fyd::string ret1;
    11. ret1 = fyd::to_string(1234);
    12. return 0;
    13. }
    14. // 运行结果:
    15. // string(string&& s) -- 移动语义
    16. // string& operator=(string&& s) -- 移动语义

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

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

     2.4 -> 右值引用引用左值及其更深入的使用场景分析

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

    1. template<class _Ty>
    2. inline typename remove_reference<_Ty>::type&& move(_Ty&& _Arg) _NOEXCEPT
    3. {
    4. // forward _Arg as movable
    5. return ((typename remove_reference<_Ty>::type&&)_Arg);
    6. }
    7. int main()
    8. {
    9. fyd::string s1("hello world");
    10. // 这里s1是左值,调用的是拷贝构造
    11. fyd::string s2(s1);
    12. // 这里我们把s1 move处理以后, 会被当成右值,调用移动构造
    13. // 但是这里要注意,一般是不要这样用的,因为我们会发现s1
    14. // 资源被转移给了s3,s1被置空了。
    15. fyd::string s3(std::move(s1));
    16. return 0;
    17. }

    2.5 -> 完美转发

    模板中的&&万能引用

    1. void Fun(int& x)
    2. {
    3. cout << "左值引用" << endl;
    4. }
    5. void Fun(const int& x)
    6. {
    7. cout << "const 左值引用" << endl;
    8. }
    9. void Fun(int&& x)
    10. {
    11. cout << "右值引用" << endl;
    12. }
    13. void Fun(const int&& x)
    14. {
    15. cout << "const 右值引用" << endl;
    16. }
    17. // 模板中的&&不代表右值引用,而是万能引用,其既能接收左值又能接收右值。
    18. // 模板的万能引用只是提供了能够接收同时接收左值引用和右值引用的能力,
    19. // 但是引用类型的唯一作用就是限制了接收的类型,后续使用中都退化成了左值,
    20. // 我们希望能够在传递过程中保持它的左值或者右值的属性
    21. template<typename T>
    22. void PerfectForward(T&& t)
    23. {
    24. Fun(t);
    25. }
    26. int main()
    27. {
    28. PerfectForward(10); // 右值
    29. int a;
    30. PerfectForward(a); // 左值
    31. PerfectForward(std::move(a)); // 右值
    32. const int b = 8;
    33. PerfectForward(b); // const 左值
    34. PerfectForward(std::move(b)); // const 右值
    35. return 0;
    36. }

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

    1. void Fun(int& x)
    2. {
    3. cout << "左值引用" << endl;
    4. }
    5. void Fun(const int& x)
    6. {
    7. cout << "const 左值引用" << endl;
    8. }
    9. void Fun(int&& x)
    10. {
    11. cout << "右值引用" << endl;
    12. }
    13. void Fun(const int&& x)
    14. {
    15. cout << "const 右值引用" << endl;
    16. }
    17. // std::forward<T>(t)在传参的过程中保持了t的原生类型属性。
    18. template<typename T>
    19. void PerfectForward(T&& t)
    20. {
    21. Fun(std::forward<T>(t));
    22. }
    23. int main()
    24. {
    25. PerfectForward(10); // 右值
    26. int a;
    27. PerfectForward(a); // 左值
    28. PerfectForward(std::move(a)); // 右值
    29. const int b = 8;
    30. PerfectForward(b); // const 左值
    31. PerfectForward(std::move(b)); // const 右值
    32. return 0;
    33. }

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

    1. template<class T>
    2. struct ListNode
    3. {
    4. ListNode* _next = nullptr;
    5. ListNode* _prev = nullptr;
    6. T _data;
    7. };
    8. template<class T>
    9. class List
    10. {
    11. typedef ListNode<T> Node;
    12. public:
    13. List()
    14. {
    15. _head = new Node;
    16. _head->_next = _head;
    17. _head->_prev = _head;
    18. }
    19. void PushBack(T&& x)
    20. {
    21. //Insert(_head, x);
    22. Insert(_head, std::forward<T>(x));
    23. }
    24. void PushFront(T&& x)
    25. {
    26. //Insert(_head->_next, x);
    27. Insert(_head->_next, std::forward<T>(x));
    28. }
    29. void Insert(Node* pos, T&& x)
    30. {
    31. Node* prev = pos->_prev;
    32. Node* newnode = new Node;
    33. newnode->_data = std::forward<T>(x); // 关键位置
    34. // prev newnode pos
    35. prev->_next = newnode;
    36. newnode->_prev = prev;
    37. newnode->_next = pos;
    38. pos->_prev = newnode;
    39. }
    40. void Insert(Node* pos, const T& x)
    41. {
    42. Node* prev = pos->_prev;
    43. Node* newnode = new Node;
    44. newnode->_data = x; // 关键位置
    45. // prev newnode pos
    46. prev->_next = newnode;
    47. newnode->_prev = prev;
    48. newnode->_next = pos;
    49. pos->_prev = newnode;
    50. }
    51. private:
    52. Node* _head;
    53. };
    54. int main()
    55. {
    56. List<fyd::string> lt;
    57. lt.PushBack("1111");
    58. lt.PushFront("2222");
    59. return 0;
    60. }

    感谢各位大佬支持!!!

    互三啦!!!

  • 相关阅读:
    H5如何实现唤起APP
    iOS13以后 获取KeyWindow
    分享2022上半年我读过的7本书
    Vue学习:回顾Object.defineProperty(给对象添加或者定义属性的)
    vue当中的mixin混入、插件使用
    优雅地记录http请求和响应的数据
    SpringBoot配置Druid
    vue3实现导出Excel(2)
    [DASCTF 7月赛] 复现
    Xshell工具连接本地虚拟机Linux系统
  • 原文地址:https://blog.csdn.net/weixin_74809706/article/details/138084578