Dir*_*leg 7 c++ pointers const auto c++11
我有这个代码:
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'
Run Code Online (Sandbox Code Playgroud)
为什么可以分配新地址b而不是c?
son*_*yao 13
b将推断为const int*,这意味着指向一个非常量指针const int,因此可以更改b自身的值.
c将推断为const int * const,这意味着一个const指针指向const int,因此您无法更改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是c自身的限定符const auto c.