C++:引用和指针的_实现_有任何巨大差异

发布于 2024-12-09 23:49:57 字数 154 浏览 1 评论 0原文

我发现我使用参考文献时并不理解它们的真正工作原理(这就是为什么我不经常使用它们)。

指针似乎是以某种方式简单地实现的:一个带有其他变量地址的简单 WORD 变量。当我们将它作为参数传递给函数时,我们会复制它。

当我们将引用作为参数传递时会发生什么?还用老办法吗?

I caught that I use references not understanding how they really work (that's why I use them not so often).

Pointer seem to be implemented simply somehow like: a simple WORD variable with address of some other variable. We copy it when we pass it as a parameter to function.

And what happens when we pass reference as a parameter? The same old way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦初启 2024-12-16 23:49:57

事实上,两者并没有你想象的那么多共同点。

引用存在于编译器中更高的抽象级别。它根本不需要生成任何代码。它本质上是对象的别名,因此每当使用它时,编译器都会将其视为对引用对象的使用。当然,有时,编译器会选择通过生成可以根据需要传递的指针值来表示使用引用的代码,但引用实际上并不与特定表示绑定。

指针更接近金属。它是一个存储地址的变量。

The two don't have as much in common as you'd think, really.

A reference exists at a higher level of abstraction in the compiler. It doesn't need to generate any code at all. It is essentially an alias for an object, so whenever it is used, the compiler treats it as a use of the referenced object. Of course, sometimes, the compiler will choose to represent code which uses a reference by generating a pointer value which can be passed around as needed, but a reference is really not tied to a specific representation.

A pointer is much more close to the metal. It is a variable which stores an address.

浪漫之都 2024-12-16 23:49:57

它们如何实现的细节取决于它们的使用环境。如果引用仅在某个范围内有效,则编译器可以删除引用(别名)并在需要时使用引用的对象。

如果不能证明引用不会逃逸当前作用域(如在可以动态分配的类的成员中),则大多数编译器使用在使用时自动取消引用的指针来实现它(并提供其余的保证)可供参考,不适用于普通指针)。

On the particulars of how they are implemented, it depends on the context in which they are used. If the reference is valid only within a scope, the compiler can remove the reference (alias) and use the referred object whenever needed.

If the reference cannot be proven not to escape the current scope (as in a member of a class that could be dynamically allocated), most compilers implement it with a pointer that is automatically dereferenced on use (and providing the rest of the guarantees that are available for references and not for plain pointers).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文