简体   繁体   中英

auto type specifier ignores top-level const

I stumbled upon this question while reading "C++ Primer", by Lippman et al. (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.

Pg. 69 of this book goes to say,

"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). Whereas I expected c to be of the type const int as there is a low-level const on cr.

Please help me understand this.

Think of the top-level as it relates to the resulting type of the auto variable. If it was going to be const int it instead will be int .

If it was going to be const int* const it instead will be const int* .

In simple terms, the top level const is the one that applies to the object itself. 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 .

The rules are designed to be useful. Removing the top most const makes auto applicable in such common cases:

const int x = 5;
auto y = x;
++y;

Usually C++ defaults to non-const. You need to specifiy it when you want to declare y as const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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