1 auto会忽略顶层const,保留底层const
2
3 int i = 0;
4
5 const int* const p = &i;
6
7 auto p2 = p; //p2是const int*,不是const int* const
8 //*p2 = 4; //错误,p指向常量
9 p2 = nullptr; //正确,p2本身不是常量
10
11
12 auto不会保留引用类型,应该使用auto&
13
14 int& x = i;
15
16 auto m = x; //m是int,不是int&
17 auto& n = x; //n是int&
18
19
20 decltype(variable)回保留顶层const和底层const
21
22 decltype(p) p3 = p; //p3是const int* const
23 //*p3 = 4; //错误
24 //p3 = nullptr; //错误
25
26
27 decltype也会保留引用类型,decltype((variable)) 双括号的结果永远是引用
28
29 int* p = &i;
30
31 decltype(*p) r = i; //解引用指针得到引用类型
32 decltype((i)) r = i; //引用
33 decltype(r+0) b; // 通过r+0可以得到int
34 decltype(*p+0) c; //意思同上
35
36
37 用auto和decltype定义复杂的函数返回类型
38
39 int array[10]; //array数组,下面定义一个函数,返回这个数组的指针
40 int (* func())[10]; //以前的定义方法
41 auto func2()->int(*)[10]; //C++11 尾置返回类型(星号必须加括号)
42 decltype(array)* func3(); //用decltype
43
44
45 定义函数指针
46
47 int fun(int); //函数,下面定义函数指针
48 int (*ffun)(int); //以前的方法
49 auto f1(int)->int(*)(int); //用auto
50 decltype(fun)* f2(int); //用decltype
51 decltype(x) z = i;
52
53 z=1986;
54
55 cout<<i<<endl; // i=1986