C++ auto 用法

转自 https://blog.csdn.net/huang_xw/article/details/8760403

    C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。

1. 自动类型推断


    auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。

  
  
  1. #include <vector>
  2. #include <map>
  3. using namespace std;
  4. int main(int argc, char argv[], char *env[])
  5. {
  6. // auto a; // 错误,没有初始化表达式,无法推断出a的类型
  7. // auto int a = 10; // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。
  8. // 1. 自动帮助推导类型
  9. auto a = 10;
  10. auto c = 'A';
  11. auto s("hello");
  12. // 2. 类型冗长
  13. map< int, map< int, int> > map_;
  14. map< int, map< int, int>>::const_iterator itr1 = map_.begin();
  15. const auto itr2 = map_.begin();
  16. auto ptr =
  17. {
  18. std:: cout << "hello world" << std:: endl;
  19. };
  20. return 0;
  21. };
  22. // 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,
  23. // 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。
  24. template < class T, class U>
  25. void Multiply(T t, U u)
  26. {
  27.      auto v = t u;
  28. }

2. 返回值占位


  
  
  1. template < typename T1, typename T2>
  2. auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)
  3. {
  4. return t1+t2;
  5. }
  6. auto v = compose( 2, 3.14); // v's type is double

3.使用注意事项

①我们可以使用valatile,pointer(),reference(&),rvalue reference(&&) 来修饰auto


  
  
  1. auto k = 5;
  2. auto pK = new auto(k);
  3. auto * ppK = new auto(&k);
  4. const auto n = 6;
②用auto声明的变量必须初始化
auto m; // m should be intialized  
  
  
③auto不能与其他类型组合连用
auto int p; // 这是旧auto的做法。
  
  
④函数和模板参数不能被声明为auto

  
  
  1. void MyFunction(auto parameter){} // no auto as method argument
  2. template< auto T> // utter nonsense - not allowed
  3. void Fun(T t){}
⑤定义在堆上的变量,使用了auto的表达式必须被初始化

  
  
  1. int p = new auto( 0); //fine
  2. int* pp = new auto(); // should be initialized
  3. auto x = new auto(); // Hmmm ... no intializer
  4. auto* y = new auto( 9); // Fine. Here y is a int*
  5. auto z = new auto( 9); //Fine. Here z is a int* (It is not just an int)
⑥以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid

  
  
  1. int value = 123;
  2. auto x2 = ( auto)value; // no casting using auto
  3. auto x3 = static_cast< auto>(value); // same as above
⑦定义在一个auto序列的变量必须始终推导成同一类型
auto x1 = 5, x2 = 5.0, x3='r';  // This is too much....we cannot combine like this
  
  
⑧auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型

  
  
  1. const int i = 99;
  2. auto j = i; // j is int, rather than const int
  3. j = 100 // Fine. As j is not constant
  4. // Now let us try to have reference
  5. auto& k = i; // Now k is const int&
  6. k = 100; // Error. k is constant
  7. // Similarly with volatile qualifer
⑨auto会退化成指向数组的指针,除非被声明为引用

  
  
  1. int a[ 9];
  2. auto j = a;
  3. cout<< typeid(j).name()<< endl; // This will print int*
  4. auto& k = a;
  5. cout<< typeid(k).name()<< endl; // This will print int [9]



猜你喜欢

转载自blog.csdn.net/qq_26598445/article/details/80929912
今日推荐