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

mar*_*rde 4 c++ pointers const reference

当一个将两个变量别名为

int a;
const int &b = a;
Run Code Online (Sandbox Code Playgroud)

这两个变量实际上是相同的,因此应用于变量的任何更改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;
}
Run Code Online (Sandbox Code Playgroud)

现在变量a似乎不是变量的别名b,但为什么呢?

son*_*yao 12

const int *const &是对const指针的引用const int.(尝试从右向左阅读.)注意指针的类型是const int *,但不是int *(即类型a).引用不能直接绑定到不同的类型.对于const int *const &b = a;临时*(带有类型const int *,从中复制a)将构造然后绑定到引用; 临时与此无关a,因此任何修改b都不会起作用a.

注意区别.在第1个样本中,const是quafied int; 在第二个示例中,const不仅限制了指针本身,还限定了指针,它使两个指针成为不同的类型(int *vs. const int *).如果你想要获得const它的资格(这对你的实验来说似乎是不必要的)你应该只在指针本身上限定它,即int * const &.


*临时的生命周期延长到参考的生命周期b.


klu*_*utt 5

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

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