[深入理解C++11:C++11新特性解析与应用] 学习笔记
auto 类型推导
auto声明变量的类型由编译器在编译时期推导而得。
基本用法:
int main() { double foo(); auto x = 1; //x的类型为int auto y = foo(); //y的类型为double struct m { int i; }str; auto str1 = str; //str1的类型为struct m auto z; //无法推导,无法通过编译 }
auto使用细则:
1. auto类型指示符与指针和引用之间的关系
在C++11中,auto可以与指针和引用结合起来使用,示例如下:
int x; int *y = &x; double foo(); int &bar(); auto *a = &x; //int* auto &b = x; //int& auto c = y; //int* auto *d = y; //int* auto *e = &foo(); //编译失败,指针不能指向一个临时变量的地址 auto &f = foo(); //编译失败,nonconst的左值引用不能和一个临时变量绑定 auto g = bar(); //int auto &h = bar(); //int&
本例中,a、c、d的类型都是指针类型,且都指向变量x。实际上,对于a、c、d三个变量而言,声明为 auto * 或 auto 并没有区别。而如果要使得auto声明的变量是另一个变量的引用,则必须使用 auto &,如同本例中的变量b和h一样。
2. auto 与 valatile 和 const 之间的联系
volatile 和 const 代表了变量的两种不同的属性:易失性和常量的。在C++标准中,它们常常被一起叫作cv限制符(cv-qualifier)。C++11标准规定 auto 可以与cv限制符一起使用,不过声明为 auto的变量病不能从其初始化表达式中“带走” cv限制符。示例如下:
double foo(); float *bar(); const auto a = foo(); //a: const double const auto &b = foo(); //b: const double & volatile auto *c = bar(); //c: valatile float * auto d = a; //d: double auto &e = a; //e: const dbouel & auto f = c; //f: float * volatile auto &g = c; //g: volatile float * &
本例中,我们可以通过非cv限制的类型初始化一个cv限制的类型,如变量a、b、c所示。不过通过auto声明的变量d、f却无法带走a和c的常量性或者易失性。这里的例外还是引用,声明为引用的变量e、g都保持了其引用的对象相同的属性(事实上,指针也是一样的)。
3. 同一个赋值语句中,auto 可以用来声明多个变量的类型,不过这些变量的类型必须相同。如果这些变量的类型不相同,编译器则会报错。事实上,用 auto 来声明多个变量类型时,只有第一个变量用于 auto 的类型推导,然后推导出来的数据类型被作用于其他的变量。
auto x = 1, y = 2; //x和y的类型均为int //m是一个指向const int类型变量的指针,n是一个int类型的变量 const auto *m = &x, n = 1; auto i = 1, j = 3.14f; //编译失败
4. C++11新引入的初始化列表,以及new,都可以使用auto关键字
auto x = 1; auto x1(1); auto y{1}; //使用初始化列表的auto auto z = new auto(1); //用于new
5. 不能使用 auto 推导的4种情况(编译器报错)
1)auto 不能用于函数形参类型。
2)对于结构体来说,非静态成员变量的类型不能是 auto 的。
3)auto 能不声明数组类型。
4)在实例化模版的时候不能使用 auto 作为模版参数。
void fun (auto x = 1) {} //1: auto 函数参数,无法通过编译 struct str { auto var = 10; //2:auto非静态成员变量,无法通过编译 }; int main() { char x[3]; auto y = x; auto z[3] = x; //3:auto数组,无法通过编译 vector<auto> v = {1}; //4:auto模版参数(实例化时),无法通过编译 }
decltype
未完待续
原文:https://www.cnblogs.com/nnmobi/p/10595579.html