在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?

In C++, if "int a = 3; int* p = &a;", then why is "const int* &pp = p" not allowed, but "const int* const &pp = p" is allowed?

本文关键字:int const pp C++ 不允许 如果 为什么      更新时间:2023-10-16

在C++中,如果:

int a = 3; 
int* p = &a; 

那为什么

const int* &pp = p; 

不允许,但

const int* const &pp = p; 

允许吗?

给定const int* &pp = p;p首先必须隐式转换为const int*。但是转换后的const int*是临时的,不能绑定到非常量(如const int* &(的左值引用。

临时可以绑定到常量(如const int* const &(的左值引用(和右值引用(,因此const int* const &pp = p;工作正常。并且临时的生存期延长至参考pp的生存期。

当常量在*左边时,常量修饰符点最远,当常量在*右边时,常量修饰符点,并且你质疑,局部var shoule的地址是常量。

不允许第一次转换的原因是它(巧妙地和不直观地(破坏了常量正确性。这里有一个讨论。简而言之,问题是这样的:

const int x;
int* p;
const int** q = &p;
*q = &x;
*p = 3;

如果第三行有效,第四行将p设置为指向x(因为*qp(,所以*p = 3会修改x,即使xconst

当顶级修饰符是引用而不是指针时,会出现同样的问题。

在多层指针类型中修改const限定符时,必须全有或全无。