C++11中引入的auto主要有两种用途:自动类型推导和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。新的 auto 关键字在声明一些迭代器、类模板等变量的时候,使用非常方便,具体可以看以下代码,有详细的注释。

#include
#include
#include

using namespace std;

int main( int argc, char* argv[])
{
list list_string;
// 传统方式定义迭代器的变量
list::iterator it = list_string.begin();
// 使用auto定义迭代器变量
for ( auto auto_it = list_string.begin();
auto_it != list_string.end();
it++ )
{
//……………..
}

  // new的内存也一定要初始化,否则auto推倒不出到底是什么类型
  auto k = 5;
  auto\* pk = new auto(5);

  // auto 关键字声明的变量必须初始化,在一行时必须使用相同数据类型初始化
  int a, b, c;
  auto aa = 0, ab = 10, ac = 20;

  // auto 引用类型可以接受 const 变量的反推,其他形式则不行
  const int consta = 0;
  auto constb = consta;

  return 0;

}

使用 auto 关键字有以下几点注意事项: 1、可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto

auto k = 5;
auto* pK = new auto(k);
auto** ppK = new auto(&k);
const auto n = 6;

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

auto m; // m should be intialized

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

auto int p; // 这是旧auto的做法

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

void MyFunction( auto parameter){} // no auto as method argument
template // utter nonsense - not allowed
void Fun(T t){}

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

int* p = new auto(0); //fine
int* pp = new auto(); // should be initialized
auto x = new auto(); // no intializer
auto* y = new auto(9); // Fine. Here y is a int*
auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)

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

int value = 123;
auto x2 = (auto)value; // no casting using auto
auto x3 = static_cast(value); // same as above

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

auto x1 = 5, x2 = 5.0, x3 = ‘r’; // This is too much….we cannot combine like this

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

const int i = 99;
auto j = i; // j is int, rather than const int
j = 100; // Fine. As j is not constant
// Now let us try to have reference
auto& k = i; // Now k is const int&
k = 100; // Error. k is constant
// Similarly with volatile qualifer

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

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

【decltype 关键字】

可以根据一个表达式或者根据一个变量推出类型。

#include
#include
#include

using namespace std;

void func01(){}

int main( int argc, char* argv[])
{
int declA;
// 通过declA 变量反推出类型,然后根据这个反推出来的类型声明新的变量
decltype(declA) declB;
// 通过func01函数指针反推出类型,然后根据这个类型声明新的函数指针 *declC
decltype(func01) *declC;

  return 0;

}