当前位置:   article > 正文

C++11中auto的使用_c++11 auto

c++11 auto

在C语言中,就有了auto关键字,它被当作是一个变量的存储类型修饰符,表示自动变量(局部变量)。它不能被单独使用,否则编译器会给出警告。在C++11标准中,添加了新的类型推导特性。在C ++11中,使用auto定义的变量不能使用其它类型修饰符修饰,该变量的类型由编译器根据初始化数据自动确定。

C++中类型检查是在编译阶段。动态类型语言能做到在运行时决定类型,主要归功于一技术,这技术是类型推导。在C++11中,可以通过重定义auto关键字来实现类型推导。

         在C++11中,使用auto关键字可以要求编译器对变量的类型进行自动推导。

         auto关键字:类型推导,从该关键字的初始化表达式中推导变量的类型。

         在块作用域、命名空间作用域、for循环的初始化语句内声明变量的时候,变量的类型可以被省略,使用关键字auto来代替。

         auto声明的变量必须被初始化,以使编译器能够从其初始化表达式中推导出其类型。

         声明为auto的变量在编译时期就分配了内存,而不是到了运行时期,所以使用auto不再引发任何速度延迟,这也意味着使用auto的时候,这个变量不初始化会报错,因为编译器无法知道这个变量的类型。

         auto使用时需注意:

         (1)、可以使用const、volatile、pointer(*)、reference(&)、rvalue reference(&&)等说明符和声明符来修饰auto关键字;

         (2)、用auto声明的变量必须初始化;

         (3)、auto不能与其它任何类型说明符一起使用;

         (4)、方法、参数或模板参数不能被声明为auto;

         (5)、定义在堆上的变量,使用了auto的表达式必须被初始化;

         (6)、auto是一个占位符,不是类型,不能用于类型转换或其它一些操作,如sizeof、typeid;

         (7)、auto关键字内声明的声明符列表的所有符号必须解析为同一类型;

         (8)、auto不能自动推导成CV-qualifiers(constant& volatile qualifiers),除非被声明为引用类型;     

         (9)、auto会退化成指向数组的指针,除非被声明为引用;

         (10)、auto不能作为函数的返回类型,在C++14中是可以的。

         建议:大多数情况使用关键字auto,除非非常需要转换。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

  1. #include "auto.hpp"
  2. #include <iostream>
  3. #include <cmath>
  4. #include <typeinfo>
  5. #include <string>
  6. #include <map>
  7. #include <list>
  8. #include <deque>
  9. #include <vector>
  10. //
  11. // reference: http://en.cppreference.com/w/cpp/language/auto
  12. template<class T, class U>
  13. auto add(T t, U u) -> decltype(t + u) // the return type is the type of operator+(T, U)
  14. {
  15. return t + u;
  16. }
  17. auto get_fun(int arg) -> double(*)(double) // same as: double (*get_fun(int))(double)
  18. {
  19. switch (arg) {
  20. case 1: return std::fabs;
  21. case 2: return std::sin;
  22. default: return std::cos;
  23. }
  24. }
  25. int test_auto1()
  26. {
  27. auto a = 1 + 2;
  28. std::cout << "type of a: " << typeid(a).name() << '\n'; // type of a: int
  29. auto b = add(1, 1.2);
  30. std::cout << "type of b: " << typeid(b).name() << '\n'; // type of b: double
  31. auto c = { 1, 2 };
  32. std::cout << "type of c: " << typeid(c).name() << '\n'; // type of c: class std::initializer_list<int>
  33. auto my_lambda = [](int x) { return x + 3; };
  34. std::cout << "my_lambda: " << my_lambda(5) << '\n'; // my_lambda: 8
  35. auto my_fun = get_fun(2);
  36. std::cout << "type of my_fun: " << typeid(my_fun).name() << '\n'; // type of my_fun: double (__cdecl*)(double)
  37. std::cout << "my_fun: " << my_fun(3) << '\n'; // my_fun: 0.14112
  38. // auto int x; // error as of C++11: "auto" is no longer a storage-class specifier // error C3530: “auto”不能与任何其他类型说明符组合
  39. return 0;
  40. }
  41. // reference: https://msdn.microsoft.com/zh-cn/library/dd293667(v=vs.120).aspx
  42. int f(int x) { return x; }
  43. int test_auto2()
  44. {
  45. int count = 10;
  46. int& countRef = count;
  47. auto myAuto = countRef;
  48. countRef = 11;
  49. std::cout << count << " " << std::endl; // 11
  50. myAuto = 12;
  51. std::cout << count << std::endl; // 11
  52. // 1. 下面的声明等效。 在第一个语句中,声明 j 变量为类型 int。 在第二个语句,因为初始化表达式 (0) 是整数,所以变量 k 推导为 int 类型
  53. int j = 0; // Variable j is explicitly type int.
  54. auto k = 0; // Variable k is implicitly type int because 0 is an integer.
  55. // 2. 以下声明等效,但第二个声明比第一个简单
  56. std::map<int, std::list<std::string>> m;
  57. std::map<int, std::list<std::string>>::iterator i = m.begin();
  58. auto i_ = m.begin();
  59. // 3. 声明 iter 和 elem 变量类型
  60. std::deque<double> dqDoubleData(10, 0.1);
  61. for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter) { /* ... */}
  62. // prefer range-for loops with the following information in mind
  63. // (this applies to any range-for with auto, not just deque)
  64. for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples
  65. { /* ... */ }
  66. for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE
  67. { /* ... */ }
  68. for (const auto& elem : dqDoubleData) // observes elements IN-PLACE
  69. { /* ... */ }
  70. // 4. 使用 new 运算符
  71. double x = 12.34;
  72. auto *y = new auto(x), **z = new auto(&x);
  73. // 5. 所有符号解析为同一类型
  74. auto x_ = 1, *y_ = &x_, **z_ = &y_; // Resolves to int.
  75. auto a(2.01), *b(&a); // Resolves to double.
  76. auto c = 'a', *d(&c); // Resolves to char.
  77. auto m_ = 1, &n_ = m_; // Resolves to int.
  78. // 6. 使用条件运算符 (?:)
  79. int v1 = 100, v2 = 200;
  80. auto e = v1 > v2 ? v1 : v2;
  81. // 7. 将变量 x7 初始化类型 int,将引用的变量 y7 初始化为类型 const int,及将变量 fp 初始化为指向返回类型 int 的函数的指针
  82. auto x7 = f(0);
  83. const auto & y7 = f(1);
  84. int(*p)(int x7);
  85. p = f;
  86. auto fp = p;
  87. return 0;
  88. }
  89. /
  90. // reference: http://www.learncpp.com/cpp-tutorial/4-8-the-auto-keyword/
  91. int add_3(int x, int y)
  92. {
  93. return x + y;
  94. }
  95. int test_auto3()
  96. {
  97. auto d = 5.0; // 5.0 is a double literal, so d will be type double
  98. auto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type int
  99. auto sum = add_3(5, 6); // add_3() returns an int, so sum will be type int
  100. return 0;
  101. }

GitHubhttps://github.com/fengbingchun/Messy_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/888702
推荐阅读
相关标签
  

闽ICP备14008679号