[英]Difference between const auto * and const auto?
我有这个代码:
const int a = 10;
const auto *b = &a; //0x9ffe34
const auto c = &a; //0x9ffe34
int z = 20;
b = &z; //0x9ffe38
//c = &z; //[Error] assignment of read-only variable 'c'
为什么可以为b
而不是c
分配新地址?
b
将推导为const int*
,这意味着指向const int
的非const指针,因此可以更改b
本身的值。
c
将推导为const int * const
,这意味着指向const int
的const指针,因此您无法更改c
本身的值。
说明
一旦确定了初始化程序的类型,编译器就会使用函数调用中的模板参数推导规则来确定将替换关键字auto的类型。
对于const auto *b = &a;
,和&a
是const int*
,然后auto
将被替换为int
,然后b
将是一个const int*
。
对于const auto c = &a;
, auto
将被替换为const int*
,然后c
将是一个const int* const
。 注意const
是const auto c
c
本身的限定符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.