C++ auto类型用法总结

转载自https://blog.csdn.net/xiaoquantouer/article/details/51647865

一、用途


auto是c++程序设计语言的关键字。用于两种情况

(1)声明变量时根据初始化表达式自动推断该变量的类型

(2)声明函数时函数返回值的占位符


二、简要理解


auto可以在声明变量时根据变量初始值的类型自动为此变量选择匹配的类型。

举例:对于值x=1;既可以声明: int x=1 或 long x=1,也可以直接声明 auto x=1


三、用法


根据初始化表达式自动推断被声明的变量的类型,如:


   
   
     
     
     
     
  1. auto f = 3.14; //double
  2. auto s("hello"); //const char*
  3. auto z = new auto( 9); //int *
  4. auto x1 = 5, x2 = 5.0, x3 = 'r'; //错误,必须是初始化为同一类型

但是,这么简单的变量声明类型,不建议用auto关键字,而是应更清晰地直接写出其类型。


auto关键字更适用于类型冗长复杂、变量使用范围专一时,使程序更清晰易读。如:


   
   
     
     
     
     
  1. std:: vector< int> vect;
  2. for( auto it = vect.begin(); it != vect.end(); ++it)
  3. { //it的类型是std::vector::iterator
  4. std:: cin >> *it;
  5. }


或者保存lambda表达式类型的变量声明:

  auto ptr = [](double x){return x*x;};//类型为std::function函数对象
   
   
     
     
     
     


四、优势


(1)拥有初始化表达式的复杂类型变量声明时简化代码。

比如:


   
   
     
     
     
     
  1. #include
  2. #include
  3. void loopover(std::vector<std::string>&vs)
  4. {
  5. std:: vector< std:: string>::iterator i=vs.begin();
  6. for(;i
  7. {
  8. }
  9. }

变为:


   
   
     
     
     
     
  1. #include
  2. #include
  3. void loopover(std::vector<std::string>&vs)
  4. {
  5. for( auto i=vs.begin();;i
  6. {
  7. }
  8. }

使用std::vector::iterator来定义i是C++常用的良好的习惯,但是这样长的声明带来了代码可读性的困难,因此引入auto,使代码可读性增加。并且使用STL将会变得更加容易


(2)可以避免类型声明时的麻烦而且避免类型声明时的错误。

但是auto不能解决所有的精度问题。比如:


   
   
     
     
     
     
  1. #include
  2. using namespace std;
  3. int main()
  4. {
  5. unsigned int a= 4294967295; //最大的unsigned int值
  6. unsigned int b= 1
  7. auto c=a+b;
  8. cout<< "a="<endl;
  9. cout<< "b="<endl;
  10. cout<< "c="<endl;
  11. }


上面代码中,程序员希望通过声明变量c为auto就能解决a+b溢出的问题。而实际上由于a+b返回的依然是unsigned int的值,姑且c的类型依然被推导为unsigned int,auto并不能帮上忙。这个跟动态类型语言中数据hi自动进行拓展的特性还是不一样的。


五、注意的地方

(1)可以用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;


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


(3)auto不能与其他类型组合连用


(4)函数和模板参数不能被声明为auto


(5)定义在堆上的变量,使用了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)


(6)以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid


(7)定义在一个auto序列的变量必须始终推导成同一类型

auto x1 = 5, x2 = 5.0, x3='r';  /"font-family: Arial, Helvetica, sans-serif;">/错误,必须是初始化为同一类型
   
   
     
     
     
     


(8)auto不能自动推导成CV-qualifiers (constant & volatile qualifiers)


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


你可能感兴趣的:(c++)