auto是类型推导关键字,两条推导规则:
int m = 0;
const auto e = m; //e -> const int
auto f = e; //f -> int
const auto& g = m; //g -> const int&
auto& h = g; //h -> const int&
1.当不声明为指针或引用时,auto的推导结果和初始化表达式抛弃引用和cv(const和volatile限定符的统称)限定符后类型一致
2.当声明为指针或引用时,auto的推导结果将保持初始化表达式的cv属性
auto的限制:
不能用于函数参数
void f(auto m = 1) //error
不能用于非静态成员变量
struct foo
{
auto val1 = 0; //error
static const auto val2 = 0; //ok
}
不能定义数组
auto f[10]; //error
不能用于模板参数
template<auto N> //error
struct foo
{
};
auto可用于简化书写,省去推导具体类型过程
std::map<int, std::string> m;
auto it = m.find(3); //ok