Auto关键字和顶级、低级常量
auto keyword and top-level, low-level constants
在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
。但是在最后一个语句中,ci
的const
没有被忽略,并且类型是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*
但没有const
或volatile
限定符的对象。二级类型,int
有const
限定符,但没有顶级类型。
int const* const ptr = ...;
定义了一个类型为int const*
且具有const
限定符的对象。第二级类型int
也有const
限定符。
int * const ptr = ...;
定义了一个类型为int*
且具有const
限定符的对象。第二级类型int
没有const
限定符。
更多信息:
c++ 11标准中"顶级cv限定符"的定义在哪里?
什么是顶级const限定符?
这是一个低级常量,因为它直接引用了它。auto b = ci
将ci
的值复制到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)
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- #定义c-预处理器常量..我做错了什么
- C++中的"inline"关键字
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 如何确保C++函数在定义之前声明(如override关键字)
- 初始化列表中常量变量的"this"关键字
- C++常量关键字异常行为
- 我应该在源文件之间共享的常量的定义中添加关键字"extern"吗
- C++ - 方法和重载中的常量关键字
- 常量关键字用法C++
- 最小特权原则和常量关键字
- 如果您已经知道变量应该是常量,那么为什么要使用关键字const呢
- Volatile关键字允许访问UnitTest++中的常量结构
- 常量关键字和重复方法签名
- 函数头中的常量和静态关键字之间的区别
- Auto关键字和顶级、低级常量
- 清单常量与C++关键字"const"