c++ - 在 C++ 中引入引用背后的基本原理到底是什么?

标签 c++ reference language-design

根据我最近的问题 (Why is a c++ reference considered safer than a pointer?) 中发生的讨论,它在我脑海中提出了另一个问题:在 C++ 中引入引用背后的基本原理到底是什么?

最佳答案

Stroustrup 的第 3.7 节 Design and Evolution of C++描述了在语言中引入引用。如果您对 C++ 的任何特性背后的基本原理感兴趣,我强烈推荐这本书。

References were introduced primarily to support operator overloading. Doug McIlroy recalls that once I was explaining some problems with a precursor to the current operator overloading scheme to him. He used the word reference with the startling effect that I muttered "Thank you," and left his office to reappear the next day with the current scheme essentially complete. Doug had reminded me of Algol68.

C passes every function argument by value, and where passing an object by value would be inefficient or inappropriate the user can pass a pointer. This strategy doesn't work where operator overloading is used. In that case, notational convenience is essential because users cannot be expected to insert address-of operators if the objects are large. For example:

a = b - c;

is acceptable (that is, conventional) notation, but

a = &b - &c;

is not. Anyway, &b - &c already has a meaning in C, and I didn't want to change that.

It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized, 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++.

关于c++ - 在 C++ 中引入引用背后的基本原理到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716426/

相关文章:

c++ - 转换无符号整数 *' to ' 无符号整数 *&

c++ - C++中的仅调试ostreams?

c++ - 在 C++ 中使用对引用的引用的目的是什么?

c++ - 常量引用 - C++

python - 为什么 python 使用 .而不是/用于导入语句中的路径?

c++ - 大数求和

ios - UITableViewCell 作为参数不是副本吗?

java - 在 Java 中,比较对象和常量值时, "=="是装箱还是拆箱?

c# - 为什么向字符串添加 null 是合法的?

c# - 一般 C# 问题