本教程说,
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/