为什么引用不能在 C++ 中重新安装
C++ 引用有两个属性:
C++ references have two properties:
- 它们总是指向同一个对象.
- 它们不能为 0.
指针正好相反:
- 它们可以指向不同的对象.
- 它们可以是 0.
为什么在 C++ 中没有不可为空的、可重置的引用或指针"?我想不出一个很好的理由为什么引用不应该被重新安装.
Why is there no "non-nullable, reseatable reference or pointer" in C++? I can't think of a good reason why references shouldn't be reseatable.
这个问题经常出现,因为当我想确保关联"(我在这里避免使用引用"或指针"这两个词)永远不会无效时,我通常会使用引用.
The question comes up often because I usually use references when I want to make sure that an "association" (I'm avoiding the words "reference" or "pointer" here) is never invalid.
我认为我从来没有想过这个 ref 总是指同一个对象,这很棒".如果引用是可重新安装的,则仍然可以获得如下所示的当前行为:
I don't think I ever thought "great that this ref always refers to the same object". If references were reseatable, one could still get the current behavior like this:
int i = 3;
int& const j = i;
这已经是合法的 C++,但毫无意义.
This is already legal C++, but meaningless.
我这样重申我的问题:'引用是对象'设计背后的基本原理是什么?为什么引用被认为是有用的总是是同一个对象,而不是仅在声明为 const 时?"
I restate my question like this: "What was the rationale behind the 'a reference is the object' design? Why was it considered useful to have references always be the same object, instead of only when declared as const?"
干杯,菲利克斯
推荐答案
Stroustrup 的C++ 的设计与演进"中给出了 C++ 不允许您重新绑定引用的原因:
The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" :
在初始化后无法更改引用所指的内容.也就是说,一旦 C++ 引用被初始化,以后就不能再引用不同的对象;它不能重新绑定.我过去曾被 Algol68 引用所困扰,其中 r1=r2
可以通过 r1
分配给引用的对象,也可以将新的引用值分配给 r1
(重新绑定 r1
)取决于 r2
的类型.我想在 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 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++.
相关文章