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

How "const int *const & variable" is interpreted in c++

本文关键字:const int variable 解释 C++      更新时间:2023-10-16

当将两个变量别名为

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 int const指针的引用。(尝试从右到左阅读。请注意,指针的类型是 const int * ,但不是int *(即a的类型(。引用不能直接绑定不同的类型。对于const int *const &b = a;,将构造一个临时*(类型为 const int *,从 a 复制(,然后绑定到引用;临时与a无关,所以对b的任何修改都不会影响a

请注意差异。在第一个样本中,constint上被限定;在第二个样本中,const不仅在指针本身上限定,而且在指针上限定,这使得两个指针的类型不同(int * vs. const int *(。如果你想在它上面限定const(这对你的实验来说似乎是不必要的(,你应该只在指针本身上限定它,即 int * const & .


*临时的寿命延长至参考b的寿命。

const int * const & b 表示对 const 指针的引用 const int。你想要的是int * const & b

使用这个方便的工具破译复杂的声明。 https://cdecl.org/