引用类型的定义是什么?

2022-01-05 00:00:00 reference c++

你如何以正式和严格的方式定义(解释)什么是 C++ 中的引用类型?

How do you define (explain) in a formal and strict way what is reference type in C++?

我试着用谷歌搜索,并查看了 Stroustrup 的C++ 编程语言",但我在那里没有看到这个概念的定义.

I tried to google, and looked into Stroustrup's "The C++ Programming Language", but I don't see definition of this concept there.

推荐答案

引用是一个别名,是对象的替代名称.它本身不是对象(因此不是指针,即使它们的某些用途与指针的用途重叠).

A reference is an alias, an alternate name for an object. It is not an object itself (and in that way is not a pointer, even if some of their uses overlap with uses of pointers).

参考文献对其处理有一定的限制,这与它们的非客观性有关.例如,您不能创建引用数组.它们必须在声明后立即进行初始化(绑定、固定),因为如果没有要别名的对象,它们就不可能存在.

References have certain limitations to their handling, related to their non-objectness. For example, you can't create an array of references. They have to be initialized (bound, seated) as soon as they are declared, since they can't possibly exist without an object to alias.

然而你可以存储它们,它们遵循自动变量或成员变量的规则.它们的用途之一是查看 C++ 的按值传递函数调用.

You can however store them, and they obey the rules of automatic variables or member variables. One of their uses is to poke through C++'s pass-by-value function calls.

请注意,const 引用作为别名有一个巧妙的副作用:当绑定到一个临时(即未命名)对象时,它们会给该对象一个名称,因此将其生命周期延长到引用本身的生命周期.

Note that const references have a neat side-effect of being aliases : when bound to a temporary (i.e unnamed) object, they give said object a name, and therefore extend its lifetime to that of the reference itself.

{ // Block scope
     Foo fooVal = makeFoo(); // Say makeFoo() returns a (temporary, unnamed) Foo
     // Here the temporary Foo is dead (fooVal is a copy).

     // Foo &fooRef = makeFoo(); // Error, reference is non-const
     Foo const &fooCRef = makeFoo(); // All good

     // ...

     // The second temporary is still alive
     fooCRef.doSomethingFunny(); // Works like a charm !

} // The second temporary dies with fooRef

但是请注意,有可能(尽管是人为的)对象超出范围并且引用仍然指向它.然后,您将拥有 悬空引用,不再使用它们(这样做将是未定义行为).

Beware though, it is possible (though contrived) to have an object go out of scope with references still pointing to it. You will then have dangling references, which are not to be used anymore (doing so would be Undefined Behaviour).

Foo *fooPtr = new Foo; // Here is a Foo
Foo &fooRef = *fooPtr; // Here is an alias for that Foo

delete fooPtr; // Here is the end of that Foo's life

fooRef.doSomethingFunny(); // Here comes trouble...

相关文章