c++ decltype和auto对比学习

#include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7
8 int a=1;
9 int b=2;
10 int &ra = a;
11 int *ptr = &a;
12 /*
13 *1.decltype对于括号和解引用操作符*,会解析为引用&
14 *int &ra = a;
15 *decltype(ra) da; //int &
16 *decltype(a) db; //int
17 *decltype((a)) dc;//int &,必须初始化,否则报错
18 */
19 // decltype(ra) refa; //int &,error:reference must initialized
20 decltype(a) testb; //int
21 // decltype((a)) refb; //int &,error:reference must initialized
22 // decltype(*ptr) refc;//int &,error:reference must initialized
23
24 /*
25 *2.decltype和auto对于const的处理对比
26 *decltype 保留底层const和顶层const
27 *auto只保留底层const
28 *auto不得不保留底层const是因为从底层const常量转换为没有底层const的变量是错误的
29 *const int *cpa = &i;
30 *auto a = cpa; //a是const int *
31 */
32 //顶层const,decltype保留,auto忽略
33 const int cona = 1;
34 decltype(cona) td = 1; // const int
35 auto hd = cona; //int
36 hd = 1; //ok
37 // td = 1; //error:const int read-only
38
39 //底层const,decltype保留,auto保留
40 const int *conb = &a;
41 decltype(conb) te = &a;//const int *
42 // *te = 2; //error:const int * read-only locatin
43 auto fe = conb; //const int *
44 // *fe = 3; //error:assignment of read-only location
45
46 //底层和顶层const
47 const int * const conc = &a;
48 decltype(conc) tf = &a; //const int * const
49 //tf = &b; //error:assignment of read-only variable
50 //*tf = 3; //error:assignment of read-only location
51 auto ft = conc; //const int *
52 ft = &b; //ok
53 // *ft = 4; //error:assignment of read-only location
54 return 0;
55 }
————————————————
版权声明:本文为CSDN博主「creator123123」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/creator123123/article/details/81572265

上一篇:Effective Modern C++ 之 auto和decltype的型别推导


下一篇:VS制作dll、def文件的使用、dll加入工程使用