xml*_*lmx 3 c++ standards pointers reference constants
int main()
{
int n = 1;
int* const p = &n; // ok
*p = 2; // ok as expected.
p = 0; // error as expected.
int& const m = n;
// error: 'const' qualifier may not be
// applied to a reference
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么 C++ 中没有 const 引用,就像 const 指针一样?
设计背后的原理是什么?
C++ 中的引用在几个基本方面不同于指针。区别之一是:
一旦创建了一个引用,以后就不能再引用另一个对象;它不能重新安装。这通常是用指针来完成的。
这意味着Reference是像类似(见这个答案的末尾链接)const的指针(不是指向一个常量!在C)+ ...
int a = 5;
int& m = a; // Behaves similar to int * const m = &a;
// See the link at the bottom for the differences between const pointer and reference.
Run Code Online (Sandbox Code Playgroud)
因此,您无法更改/重新绑定它们以指向其他地址。因此,您不需要显式const的引用限定符,这就是编译器不允许使用的原因。
请参阅此链接以了解Why are references not reseatable in C++?。我已复制上述链接的已接受答案:
C++ 不允许您重新绑定引用的原因在 Stroustrup 的“C++ 的设计和演化”中给出:
初始化后无法更改引用所指的内容。也就是说,一旦 C++ 引用被初始化,以后就不能再引用不同的对象;它不能重新绑定。我过去曾被 Algol68 引用所困扰,其中 r1=r2 可以通过 r1 分配给引用的对象,也可以根据 r2 的类型为 r1(重新绑定 r1)分配新的引用值。我想在 C++ 中避免这样的问题。
编辑:
请参阅此链接Difference between const pointer and reference?(感谢@MM 指出我声明中的歧义)。