Auto关键字和顶级、低级常量

auto keyword and top-level, low-level constants

本文关键字:常量 关键字 Auto      更新时间:2023-10-16

在c++ Primer中提到,auto通常忽略顶级常量。通常,在初始化过程中,会保留底层常量,例如初始化指向常量的指针时。

const int ci = i, &cr = ci; 
auto b = ci; // ok:b is an int (top level constants in ci is ignored)
auto d = &i; // d is an int* (& of a int object is int *)
auto e = &ci; // e is a const int *(& of a constant object is a low level constant)

现在,我的问题是:在第二个语句中,const被忽略,b的类型为int。但是在最后一个语句中,ciconst没有被忽略,并且类型是const int*,而不是int*。为什么?

当您使用auto b=ci;时,您创建了ci的副本,因此c++没有理由阻止您更改b的值。但是如果使用auto e=&ci;,将创建一个const int变量ci的指针。e应该是一个常量指针,以防止你改变ci的值。

的使用
const int i = ...;

来定义const对象一直是一个令人困惑的问题。这让人觉得;

const int* ptr = ...; 

还定义了一个const指针。这将是一个错误的结论。如果你移动const一点,它就不那么混乱了。

int i = ...;                 // Defines i to be a non-const object
int const i = ...;           // Defines i to be a const object
int* ptr = ...;              // Defines ptr to be a non-const pointer to a non-const object
int const* ptr = ...;        // Defines ptr to be a non-const pointer to a const object
int* const ptr = ...;        // Defines ptr to be a const pointer to a non-const object
int const* const ptr = ...;  // Defines ptr to be a const pointer to a const object

关于顶级cv-限定符的问题,

int const i = ...;

定义了一个类型为int且具有const限定符的对象。

int volatile i = ...;

定义了一个类型为int且具有volatile限定符的对象。

int const* ptr = ...;

定义了一个类型为int const*但没有constvolatile限定符的对象。二级类型,intconst限定符,但没有顶级类型。

int const* const ptr = ...;

定义了一个类型为int const*且具有const限定符的对象。第二级类型int也有const限定符。

int * const ptr = ...;

定义了一个类型为int*且具有const限定符的对象。第二级类型int没有const限定符。

更多信息:

c++ 11标准中"顶级cv限定符"的定义在哪里?
什么是顶级const限定符?

这是一个低级常量,因为它直接引用了它。auto b = cici的值复制到b,但auto e = &ci必须具有一些const -ness,因为它不复制ci,而是指向ci存在的位置。在这种情况下,"低级别"一词意味着没有太多的间接性。

你忘了提到int i=0;在这里,i可以在程序的上下文中改变,这使得它成为非常量。

在第二个语句中,const被忽略

所以,没有顶级const可以忽略

c++ Primer中的实际代码,

int i = 0;//Value of i is 0 but it might change
const int ci = i;//Value of ci will not change once initialized
auto d = &i;//Hence d is an int*(No top-level const)

在最后一条语句中,不忽略ci的const

,const对象的值是auto不会忽略的低级const

auto e = &ci;// e is const int*(low-level const)