如何在 C++ 中解释"const int *const & variable"
How "const int *const & variable" is interpreted in c++
当将两个变量别名为
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
。
请注意差异。在第一个样本中,const
在int
上被限定;在第二个样本中,const
不仅在指针本身上限定,而且在指针上限定,这使得两个指针的类型不同(int *
vs. const int *
(。如果你想在它上面限定const
(这对你的实验来说似乎是不必要的(,你应该只在指针本身上限定它,即 int * const &
.
*临时的寿命延长至参考b
的寿命。
const int * const & b
表示对 const 指针的引用 const int。你想要的是int * const & b
使用这个方便的工具破译复杂的声明。 https://cdecl.org/
相关文章:
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 在类 (C++) 之外设置 const int 成员变量
- C++ 无法从 const int* 转换为 const_iterator
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- C++如何将 std::vector 转换为 const<int> std::vector<const int>?
- 如何在字符串向量中指向const int
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 为什么允许 int 和 const int 使用不同的转换函数?
- 如何通过头文件中的函数初始化 const int 数组?
- 为什么 const int 适用于字符大括号初始化?
- 不同类型的"decltype((const int)a)"和"decltype((cons
- 为什么我不能使用与"常量字符*"相同的"const int*"创建一个 int 数组?
- Const Int 宣布与 stoi 不被视为 const
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- 杀死幻数:"const int" vs "constexpr int"(或者最后没有区别)
- 作为返回类型"const int&"做什么?
- 将const int std ::数组的n元素复制到int矢量中.怎么做
- 尝试使用 const int std::array 时出错
- 构造函数中没有从 'const int [5][4]' 到 'const int **' 的已知转换