引用数据类型的 & 符号是否返回引用本身的地址或它所引用的值

Does ampersand of reference data type return the address of the reference itself or the value it is referencing?

本文关键字:引用 地址 返回 数据类型 符号 是否      更新时间:2023-10-16

我希望我能自己测试它,但不幸的是,在我目前的情况下不可能这样做。有人愿意对此有所了解吗?

它返回它所引用的值的地址。

与指针不同,引用实际上不是对象。它本身没有地址,更容易将其视为编译器随后将解释的对象的别名。

无论如何,您可以随时使用IdeOne在线测试代码。

#include <stdio.h>
void func(int &z)
{
    printf("&z: %p", &z);
}
int main(int argc, char **argv)
{
    int x = 0;
    int &y = x;
    printf("&x: %pn", &x);
    printf("&y: %pn", &y);
    func(x);
    return 0;
}

在线执行,有结果。

值的地址。(没有参考地址这样的东西)

您可以随时在代码键盘上检查:http://codepad.org/I1aBfWAQ

进一步的实验:有在线编译器可以检查中间结果!

以 Mahmoud 在 Try out LLVM and Clang 页面上的示例为例,我们得到以下 LLVM IR(截断)。

define i32 @main() nounwind uwtable {
  %x = alloca i32, align 4
  store i32 0, i32* %x, align 4, !tbaa !0
  %1 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([8 x i8]* @.str, i64 0, i64 0), i32* %x)
  %2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([8 x i8]* @.str1, i64 0, i64 0), i32* %x)
  %3 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([7 x i8]* @.str2, i64 0, i64 0), i32* %x) nounwind
  ret i32 0
}

。语法不是太重要,重要的是注意已经声明了一个变量:%x(其名称与 C 函数的名称可疑地相似)。

这意味着编译器已省略yz变量,不会为它们分配任何存储。

我就不帮你列出;)