C++ 中 auto 和顶/底层常量的问题
大家讲道理
大家讲道理 2017-04-17 13:38:08
0
4
1077

C++ Primer 第5版中,关于 auto 让我有点疑问:

里边说

auto 通常会忽略掉顶层的 const,底层 const 则会保留下来。因此,设置一个类型为 auto 的引用时,初始值中的顶层常量属性仍然保留。但仍然要注意,如果初始值已经绑定了引用,则此常量就不是顶层常量了。

这里的顶层常量和底层常量有哪些区别,导致了这样的说法?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
阿神

You will know it by looking at the content of the const chapter. Top-level constants refer to constants whose contents are not allowed to be modified, such as const int* p; p is an integer pointer, and the pointer of the integer variable it points to cannot be modified. The const modifier is right-associative, so the const here modifies int, indicating that the content cannot be modified.
Underlying constants refer to constants whose values ​​can be modified, but whose addresses cannot be modified. For example, int* const p; The right side of const is a pointer, so this statement defines a pointer that cannot point to other memory areas, but the value of this memory area can be modified

PHPzhong
int i = 10;
int j = 5;
const int *p1 = &i;
int * const p2 = &i;
*p1 = 10; // illegal
p1 = &j;   // legal
*p2 = 7;   // legal
p2 = &j;   // illegal
伊谢尔伦

To put it simply:
Whether the pointer can be changed is a top-level const;
Whether the thing pointed to by the pointer can be changed is a bottom-level const.
Generally during the type derivation process, the top-level const will be ignored, while the bottom-level const is retained.
It is allowed to assign top-level const variables to non-top-level const variables, but not if the underlying const is different. Different underlying consts are equivalent to different types.

左手右手慢动作
1L的回答是错的
刚好说反了,您可以参考一下c++ primer第57页的内容。顶层const表示指针本身是个常量,即int *const p,而底层const则指的是指针或者引用的对象是常量,即const int*p
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template