码迷,mamicode.com
首页 > 编程语言 > 详细

c++ decltype和auto对比学习

时间:2019-10-29 11:49:05      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:article   ash   clu   decltype   include   name   oca   reference   test   

#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

c++ decltype和auto对比学习

标签:article   ash   clu   decltype   include   name   oca   reference   test   

原文地址:https://www.cnblogs.com/maoliyy/p/11757463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!