简体   繁体   English

自动类型说明符忽略顶级常量

[英]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 ,因为cint类型(c 的值可以更改为 12,编译器不会抱怨)。 Whereas I expected c to be of the type const int as there is a low-level const on cr.而我希望cconst 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 ,而顶层constconst 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM