c++ - C++ 中的引用在内部编译为指针还是别名?

标签 c++ pointers reference

本教程说,

You're probably noticing a similarity to pointers here--and that's true, references are often implemented by the compiler writers as pointers

类似地,有人评论了

What is a reference variable in C++?

作为

Technically not. If bar was a variable you could get its address. A reference is an alias to another variable (not the address of as this would imply the compiler would need to insert a dereference operation). When this gets compiled out bar probably is just replaced by foo

哪种说法是正确的?

最佳答案

两者都是正确的,但在不同的情况下。

从语义上讲,引用变量只是为对象引入了一个新名称(C++ 意义上的“对象”)。
(关于“变量”和“对象”的含义有很多混淆,但我认为许多其他语言中的“变量”在 C++ 中称为“对象”,这就是你的第二句话指“变量”。)

如果此引用未存储在任何地方或作为参数传递,则它根本不需要任何表示(编译器可以只使用它引用的任何内容)。

如果它被存储(例如作为成员)或作为参数传递,编译器需要给它一个表示,最明智的就是使用它所引用的对象的地址,这是完全相同的指针的表示方式。

请注意,标准明确表示它未指定引用变量是否具有任何大小。

关于c++ - C++ 中的引用在内部编译为指针还是别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20993147/

相关文章:

c++ - 是否可以确定堆栈上有多少可用空间?

c++ - 递增 'masked' 位集

c++ - 故障转储分析 : CxxUnhandledExceptionFilter

c++ - 在使用 pthreads 时,如何在 C++ 中将方法指针作为函数参数传递

c++ - 传递引用的指针/传递引用的引用

c++ - 转到基于范围的 for 循环中的下一个迭代器

c - 如何在结构数组中初始化和动态分配一个 int 指针成员?

c++ - 基于双向链表的双端队列实现不起作用

ruby - 传递对方法的引用后,任何使用该引用的 mod 在方法外部都不可见 - Ruby?

java - 在 GUI 元素中存储对象引用