在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?
在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
(因为*q
p
(,所以*p = 3
会修改x
,即使x
是const
。
当顶级修饰符是引用而不是指针时,会出现同样的问题。
在多层指针类型中修改const
限定符时,必须全有或全无。
相关文章:
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- int(int)& 或 int(int) const &是什么类型?
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- 如何在构造函数中初始化int const * const
- 对"displayForStudent(int, int const*, double const*, int)"的未定义引用 collect2.exe:错误:ld 返回 1 个退出状态
- 如何在 C++ 中解释"const int *const & variable"
- 为什么"int & const" MSVC 编译得很好?
- const int const&和const int&in C++有什么区别?
- std::set<int * const> 不会编译
- " invalid operands of types 'int' and 'int* const'" 来自功能的错误,来自书
- std::initializer_list<int const> 不能从 std::initializer_list <int>构造
- 对'std::string Helper::ToString<int>(int const&)'的未定义引用
- 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别
- const int* const fun(const int* const& p) const的含义;
- 为什么vector<int * const>是非法/不合逻辑的?
- 对 Stack<int>::p ush(int const&) 的未定义引用
- JsonCpp:未定义的对"Json::Value::operator[](int) const"的引用