auto
顶层const(指针本身指向不变, 如int *const)
int y = 5;
auto a1 = y; //int
auto a2 = &y; //int*
const auto a3 = &y; //int* const
auto const a4 = &y; //同上
底层const(指向的变量其本身不变, 如const int)
const int y = 5;
//初始值5本身是int值,不会把const属性一起带过去,需要自行加上
auto a1 = y; //int
const auto a2 = y; //const int
指针/引用
int x = 5;
int *y = &x;
int &z = x;
auto a1 = x; //int
auto a2 = y; //int*,y本身是个地址
auto a3 = z; //int,z可以看作x的别名
auto& a4 = z; //int&
decltype
顶层const(指针本身指向不变, 如int *const)
int x = 5;
int *const y = &x;
decltype(y) a1 = &x; //int *const
底层const(指向的变量其本身不变, 如const int)
const int x = 5;
decltype(x) a2 = x; //const int
指针/引用
int x = 5;
int *y = &x;
int &z = x;
decltype(x) a1 = 7; //int
decltype(y) a2 = &a1 //int*
decltype(z) a3 = a1; //int&
ADD:
引用->类型:
可以通过+0
的方法将引用去掉
decltype(z + 0) a3 = a1; //int
指针->引用:
对于指针,可以将其解引用来获得其引用类型
decltype(*y) a2 = a1 //int&
类型->引用:
如果需要从类型推断出引用,可多加一对括号:
decltype((x)) a1 = 7; //int&
总结
auto通过初始值推导类型,不保留const和引用,需要自行加上;
decltype可以访问到已有表达式的类型(如果表达式是函数,不需要调用函数),因此能够保留const和引用,而且还可以进行引用与类型之间的转换;