作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
当一个人将两个变量别名为
int a;
const int &b = a;
这两个变量实际上是同一事物,因此应用于变量 a
的任何更改也会应用于变量 b
。然而,当用指针完成相同的技巧时,它似乎不会以相同的方式工作,如以下程序所示:
#include <iostream>
int main(void) {
int *a = (int*) 0x1;
const int *const &b = a;// Now b should be an alias to a.
a = (int*) 0x2;// This should change b to 0x2.
std::cout << b << "\n";// Outputs 0x1 instead of the expected value of 0x2.
return 0;
}
现在变量a
似乎根本不是变量b
的别名,但为什么呢?
最佳答案
const int *const &
是对 const
的引用指向 const int
的指针. (尝试从右到左阅读。)注意指针的类型是 const int *
。 , 但不是 int *
(即 a
的类型)。引用不能直接与不同类型绑定(bind)。对于 const int *const &b = a;
一个临时的*(类型为const int *
,从a
复制)将被构造然后绑定(bind)到引用;临时与a
无关, 所以对 b
的任何修改不会影响a
.
注意区别。在第一个样本中,const
符合 int
;在第二个样本中,const
不仅在指针本身上,而且在指针对象上都是合格的,这使得两个指针的类型不同( int *
与 const int *
)。如果你想出线const
在它上面(这对你的实验来说似乎是不必要的)你应该只在指针本身上限定它,即 int * const &
.
*lifetime of the temporary延长至引用生命周期 b
.
关于c++ - 如何在 C++ 中解释 "const int *const & variable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48087428/
我是一名优秀的程序员,十分优秀!