为什么 int& 作为函数参数使用 QWORD(8 字节)内存,而 int 参数使用 DWORD

UPi*_*nar 1 c++ assembly gcc reference x86-64

在下面的代码中,

int firstFunction(int& refParam)
{
    std::cout << "Type of refParam is: " << typeid(refParam).name() << '\n';
    return refParam;
}

int secondFunction(int param)
{
    std::cout << "Type of param is: " << typeid(param).name() << '\n';
    return param;
}

int main()
{
    int firstVar{ 1 };
    int secondVar{ firstFunction(firstVar) };
    int thirdVar{ secondFunction(firstVar) };
}
Run Code Online (Sandbox Code Playgroud)

控制台输出是

int
int
Run Code Online (Sandbox Code Playgroud)

当我检查Godbolt 链接中的汇编代码时。

firstFunction(int&):
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     rax, QWORD PTR [rbp-8]
        mov     eax, DWORD PTR [rax]
        pop     rbp
        ret
secondFunction(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     eax, DWORD PTR [rbp-4]
        pop     rbp
        ret
Run Code Online (Sandbox Code Playgroud)

引用参数在第二个函数中创建 8 个字节的空间,QWORD PTR [rbp-8], rdi 而不是 4 个字节DWORD PTR [rbp-4], edi

看到eax, DWORD PTR [rax]第 6 行后,firstFunction(int&): 我认为这可能是因为前半部分(eax)存储了值地址,但是当我创建第三个函数以 char& 作为参数时,它也创建了 8 字节空间。神箭链接

这有什么理由吗?

Asp*_*oob 6

如果无法优化,引用通常会在底层实现为指针,并且指针在 64 位模式下为 8 个字节