gpt4 book ai didi

c++ - const auto * 和 const auto 之间的区别?

转载 作者:可可西里 更新时间:2023-11-01 18:19:51 29 4
gpt4 key购买 nike

我有这个代码:

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非常量指针>,所以改变 b 本身的值就可以了。

c 将被推导出为const int * const,这意味着一个const 指针指向const int , 所以你不能改变 c 本身的值。

解释

对于这种情况auto specifier将使用 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.

对于const auto *b = &a;,并且&aconst int*,那么auto会被替换为 int,那么 b 将是一个 const int*

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

关于c++ - const auto * 和 const auto 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563017/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com