[英]auto type specifier ignores top-level const
I stumbled upon this question while reading "C++ Primer", by Lippman et al.我在阅读 Lippman 等人的“C++ Primer”时偶然发现了这个问题。 (5/e) (5/e)
14 int i = 0;
15 const int ci = i, &cr = ci;
16 auto c = cr;
17
18 c = 12; // works fine
we have this code snippet.我们有这个代码片段。
in line 15 const
on ci
is top-level, const
on cr
is (as is always on references) is low-level.在第 15 行中, ci
上的const
是顶级的, cr
上的const
是(始终在引用上)是低级的。
Pg.页。 69 of this book goes to say,这本书的第69页说,
"auto ordinarily ignores top-level consts" “自动通常忽略顶级常量”
But it is ignoring low-level const
on cr
as c
is of type int
(value of c can be changed to 12 without compiler complaining).但它忽略了cr
上的低级const
,因为c
是int
类型(c 的值可以更改为 12,编译器不会抱怨)。 Whereas I expected c
to be of the type const int
as there is a low-level const
on cr.而我希望c
是const int
类型,因为 cr 上有一个低级const
。
Please help me understand this.请帮助我理解这一点。
Think of the top-level as it relates to the resulting type of the auto
variable.考虑顶层,因为它与auto
变量的结果类型相关。 If it was going to be const int
it instead will be int
.如果它是const int
那么它将是int
。
If it was going to be const int* const
it instead will be const int*
.如果它将是const int* const
那么它将是const int*
。
In simple terms, the top level const
is the one that applies to the object itself.简单来说,顶级const
是应用于对象本身的const
。 A int * const
is not const
, it is a non-const pointer to a const
, whereas a top level const
as in const int * const
makes the object itself const
.甲int * const
不是const
,这是一个非const指针const
,而顶层const
如const int * const
使对象本身const
。
The rules are designed to be useful.这些规则旨在是有用的。 Removing the top most const
makes auto
applicable in such common cases:删除最顶部的const
使auto
适用于这些常见情况:
const int x = 5;
auto y = x;
++y;
Usually C++ defaults to non-const.通常 C++ 默认为非常量。 You need to specifiy it when you want to declare y
as const
.当您想将y
声明为const
时,您需要指定它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.