1. auto关键字( C++11 )
1.0 类型别名给予启发
随着程序越来越复杂,程序中用到的类型也越来越复杂,经常体现在:
-
类型难于拼写
-
含义不明确导致容易出错
cpp
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> m{ { "apple", "苹果" }, { "orange",
"橙子" },
{"pear","梨"} };
std::map<std::string, std::string>::iterator it = m.begin();
while (it != m.end())
{
//....
}
return 0;
}
std ::map<std::string, std::string>:: iterator 是一个类型,但是该类型太长了,特别容易写错。所以可以通过typedef给类型取别名,比如:
cpp
typedef std::map<std::string, std::string> Map;
在编程时,常常需要把表达式的值赋值给变量,这就要求在声明变量的时候清楚地知道表达式的类型。然而有时候要做到这点并非那么容易,因此C++11给auto赋予了新的含义。
1.1 auto简介
在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的 局部变量,但一直没有人去使用它。
在C++11中,标准委员会赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。
即我使用 auto 初始化一个变量时,编译器自动根据我初始化时赋的值自动匹配这个变量的类型。
cpp
int TestAuto()
{
return 10;
}
int main()
{
int a = 10;
auto b = a;
auto c = 'a';
auto d = TestAuto();
auto& e = a;
auto* f = &a;
auto g = &a;
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
cout << typeid(e).name() << endl;
cout << typeid(f).name() << endl;
cout << typeid(g).name() << endl;
return 0;
}

【注意】
使用 auto 定义变量时必须对其进行初始化,在编译阶段编译器需要根据初始化表达式来推导 auto 的实际类型 。因此 auto 并非是一种"类型"的声明,而是一个类型声明时的"占位符",编译器在编译期会将 auto 替换为变量实际的类型。
1.2 auto的使用细则
1. auto与指针和引用结合起来使用
用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
2. 在同一行定义多个变量
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
cpp
void TestAuto()
{
auto a = 1, b = 2;
auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
}
1.3 auto不能推导的场景
- auto不能作为函数的参数
cpp
// 此处代码编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导
void TestAuto(auto a)
{}
- auto不能直接用来声明数组
cpp
void TestAuto()
{
int a[] = { 1,2,3 };
auto b[] = { 4,5,6 };
}
-
为了避免与C++98中的 auto 发生混淆,C++11 只保留了 auto 作为类型指示符的用法
-
auto 在实际中最常见的优势用法就是跟 C++11 提供的新式 for 循环,还有 lambda 表达式等进行配合使用。