gpt4 book ai didi

c++ - 如何在 C++ 中解释 "const int *const & variable"

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:02 25 4
gpt4 key购买 nike

当一个人将两个变量别名为

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com