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

标签 c++ pointers reference constants standards

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/

相关文章:

c++ - QT token 前缺少二元运算符 "("错误

C++ 无效转换

c++ - C++中,为什么返回不同对象私有(private)变量的指针会导致段错误?

.net - 为什么 .Net 引用类型中有接口(interface)?

c++ - 使用 Crypto++ 将文件的 CRC 计算为数值

c++ - g++ 中是否存在这样的优化?

c - 用函数修改 C 结构的子结构(用于 trie 的应用)

c++ - 如何从线程函数返回值?

django - MongoDB - MongoEngine - 如何遵循 "the other side"的引用?

c++ - 通过引用和内存使用