什么是参考类型的定义? [英] What is definition of reference type?

查看:223
本文介绍了什么是参考类型的定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试google,并查看Stroustrup的编程语言,但我没有看到这个概念的定义。

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 ++的pass-by-value函数调用。

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...

这篇关于什么是参考类型的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆