繁体   English   中英

const auto *和const auto之间的区别?

[英]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 intconst指针,因此您无法更改c本身的值。

说明

对于这种情况, auto说明符将使用模板参数推导的规则。

一旦确定了初始化程序的类型,编译器就会使用函数调用中的模板参数推导规则来确定将替换关键字auto的类型。

对于const auto *b = &a; ,和&aconst int* ,然后auto将被替换为int ,然后b将是一个const int*

对于const auto c = &a; auto将被替换为const int* ,然后c将是一个const int* const 注意constconst auto c c本身的限定符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM