C语言里面其实就已经有auto关键字了,只不过很少用到
当我们在C或者以前的C++中,auto关键字在自动存储类中声明变量,即具有局部生存期的变量,
基本上可以被无视。比如这个局部变量: int a = 100; auto int a = 100;并没有什么区别,
但是在C++11标准里面auto已经有了新的含义,可以从声明的初始化表达式中可以推导出变量的类型。
auto a = 100;等价int a = 100;
当我们在C或者以前的C++中,auto关键字在自动存储类中声明变量,即具有局部生存期的变量,
基本上可以被无视。比如这个局部变量: int a = 100; auto int a = 100;并没有什么区别,
但是在C++11标准里面auto已经有了新的含义,可以从声明的初始化表达式中可以推导出变量的类型。
auto a = 100;等价int a = 100;
在c++11中auto有两个新特性就是:自动类型推断和返回值占位,如下面的列子
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <map>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//自动类型推断
auto A = 10; //equal int a=10;
auto B = 'A';
auto C("hello");
cout<<A<<B<<C<<endl;
// 类型冗长
map<int, map<int,int> > myMap;
map<int, map<int,int>>::const_iterator itr1 = myMap.begin();
const auto itr2 = myMap.begin(); //itr2 equal itr1;
getchar();
return 0;
}
当我们不知道返回值的类型时这将是一个很炫的技能
decltype 不会执行表达式而auto会,decltype 仅仅推论一下表达式的类型
template <typename Type1, typename Type2>
auto compose(Type1 t1, Type2 t2) -> decltype(t1 + t2)
{
return t1+t2;
}
auto v = compose(10, 3.141); // v's type is double
使用时必须初始化
auto A = 10; //ok, equal int a=10;
auto B ; //bad, B shuld be intialized
同一序列上必须类型相同
auto A = 10, B = 20; //ok
auto A = 10, B = 13.5 ; //bad
函数和模板参数不能被声明为auto
void MyFunction(auto parameter){} //bad
template<auto T> // bad
void Fun(T t){} </span>
不能用于类型转化
int tmp = 123;
auto x1 = (auto)tmp; // bad
auto x2 = static_cast<auto>(tmp); //bad
指向数组时可定义为引用,否则会退化成指针
int a[9];
auto j = a;
// equal int* j= a;
auto& k = a;
// equal k[]= a[];</span></span>
auto不能制动推导成const,除非定义为引用类型
const int i=10;
auto j=i;
j=100; // ok, j is int
auto &k=i;
k=100; // bad, k is const int</span>