gpt4 book ai didi

c++ - 为什么 C++ 中没有 const 引用,就像 const 指针一样?

转载 作者:行者123 更新时间:2023-12-04 06:42:08 25 4
gpt4 key购买 nike

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;
}

为什么 C++ 中没有 const 引用,就像 const 指针一样?

设计背后的基本原理是什么?

最佳答案

References在 C++ 中,在几个基本方面与指针不同。不同之处之一是:

Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.



这意味着 Reference与 C++ 中的 const 指针( 不是指向 const 的指针! )类似(请参阅此答案末尾的链接)...
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.

因此,您不能更改/重新绑定(bind)它们以指向其他地址。因此,您不需要明确的 const引用的限定符,这就是编译器不允许它的原因。

看到这个 link学习 Why are references not reseatable in C++? .我已复制上述链接的已接受答案:

C++ 不允许您重新绑定(bind)引用的原因在 Stroustrup 的“C++ 的设计和演变”中给出:

It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign a new reference value to r1 (re-binding r1) depending on the type of r2. I wanted to avoid such problems in C++.



编辑:

this Difference between const pointer and reference? 的链接(感谢@MM 指出我声明中的歧义)。

关于c++ - 为什么 C++ 中没有 const 引用,就像 const 指针一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59639756/

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