auto关键字是C++中一个重要且常用的关键字。在初始化变量时,auto关键字用于类型推断(也称为类型推导)。
关于 auto 关键字有 3 种不同的规则。
第一条规则
auto x = expr; ----> 没有指针或引用,只有变量名。在这种情况下,const 和 reference 将被忽略。
int y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)
const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)
int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)
const int a[10] = {};
auto x = a; // x is const int *. (Array to pointer conversion)
Note : When the name defined by auto is given a value with the name of a function,
the type inference will be done as a function pointer.
第二条规则
auto& y = expr; 或auto* y = expr; ----> auto 关键字后的引用或指针。
警告: const 在此规则中不会被忽略!!! .
int y = 10;
auto& x = y; // The type of variable x is int&.
警告:在此规则中,不会发生数组到指针的转换(数组衰减)!!!。
auto& x = "hello"; // The type of variable x is const char [6].
static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier
// The type of variable x is int.
第三条规则
auto&& z = expr; ----> 这不是右值引用。
警告:如果类型推断存在问题并且使用了 && 标记,则名称
像这样引入的称为“转发引用”(也称为通用引用)。
auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression.
auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression.