C++ "const T &const" 第二个常量的含义是什么?

c++ "const T &const" What is the meaning of the 2nd const?

本文关键字:const 是什么 第二个 C++ 常量      更新时间:2023-10-16

你能解释一下下面表达式中第二个"const"的含义吗:

int i = 42;
const int &const ri = i;

有没有一些情况下const T&const是强制性的吗?

到目前为止我所理解的:指针是对象,它们可以重新分配。

int i = 42;
const int *ptr1 = &i;        // valid: (low-level const): *ptr1 cannot be changed.
int *const ptr2 = &i;        // valid: (high-level const): ptr2 cannot be changed.
const int *const ptr3 = &i:  // also valid (combination of 2 precedent lines).

引用,未链接的指针不是对象(它们没有地址),不能重新分配===>对"高级常量"没有意义

int i = 42;
int &ri1 = i;        // valid: ri1 is a new name for i
const int &ri2 = 7;  // valid and const is required
const int &ri3 = i;  // valid, what is the use of const?
const int &const ri4 = i;  // valid, has the second const an importance? 

形式int & const不正确(C++11§8.3.2):

在声明T D中,其中D具有形式之一

& attribute-specifier-seqopt D1  
&& attribute-specifier-seqopt D1

并且声明T D1中标识符的类型是"派生声明符类型列表T",则D的标识符的类型为"派生声明器类型列表对T的引用"。可选属性说明符seq属于引用类型Cv限定引用格式不正确除非Cv限定符是通过使用typedef(7.1.3)或模板类型参数(14.3)引入的,在这种情况下,Cv限定词被忽略。

所以不,它不可能在任何地方都是强制性的。而且它没有语义。