根据我最近的问题 (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 throughr1
to the object referred to or assign a new reference value tor1
(re-bindingr1
) depending on the type ofr2
. I wanted to avoid such problems in C++.
关于c++ - 在 C++ 中引入引用背后的基本原理到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716426/