I have this code:
我有这段代码:
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'
Why can you assign a new address to b
and not to c
?
为什么你可以给b分配一个新地址而不给c?
1 个解决方案
#1
12
b
will be deduced as const int*
, which means a non-const pointer pointing to const int
, so it's fine to change the value of b
itself.
b将被推断为const int*,这意味着一个指向const int的非const指针,所以改变b本身的值是可以的。
c
will be deduced as const int * const
, which means a const pointer pointing to const int
, so you couldn't change the value of c
itself.
c将被推断为const int * const,这意味着const指针指向const int,所以你不能改变c本身的值。
Explanation
解释
For this case auto specifier will use the rules for template argument deduction.
对于这种情况,自动说明符将使用模板参数演绎规则。
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call.
一旦确定了初始化器的类型,编译器将使用函数调用中的模板参数演绎规则确定替换关键字auto的类型。
For const auto *b = &a;
, and &a
is const int*
, then auto
will be replaced as int
, then b
will be a const int*
.
对于const auto *b = &a, and &a为const int*,则自动替换为int,则b为const int*。
For const auto c = &a;
, auto
will be replaced as const int*
, then c
will be a const int* const
. Note the const
is the qualifier on c
itself in const auto c
.
对于const auto c = &a,将auto替换为const int*,则c为const int* const。注意const是const auto c中c本身的限定符。
#1
12
b
will be deduced as const int*
, which means a non-const pointer pointing to const int
, so it's fine to change the value of b
itself.
b将被推断为const int*,这意味着一个指向const int的非const指针,所以改变b本身的值是可以的。
c
will be deduced as const int * const
, which means a const pointer pointing to const int
, so you couldn't change the value of c
itself.
c将被推断为const int * const,这意味着const指针指向const int,所以你不能改变c本身的值。
Explanation
解释
For this case auto specifier will use the rules for template argument deduction.
对于这种情况,自动说明符将使用模板参数演绎规则。
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call.
一旦确定了初始化器的类型,编译器将使用函数调用中的模板参数演绎规则确定替换关键字auto的类型。
For const auto *b = &a;
, and &a
is const int*
, then auto
will be replaced as int
, then b
will be a const int*
.
对于const auto *b = &a, and &a为const int*,则自动替换为int,则b为const int*。
For const auto c = &a;
, auto
will be replaced as const int*
, then c
will be a const int* const
. Note the const
is the qualifier on c
itself in const auto c
.
对于const auto c = &a,将auto替换为const int*,则c为const int* const。注意const是const auto c中c本身的限定符。