英文:
why int& as function parameter uses QWORD(8 byte) memory but int parameter uses DWORD
问题
在下面的代码中:
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) };
}
控制台输出为:
int
int
当我在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
引用参数在内存中创建了8字节的空间 QWORD PTR [rbp-8], rdi
,而第二个函数中只创建了4字节的空间 DWORD PTR [rbp-4], edi
。
在firstFunction(int&)
的第6行看到 eax, DWORD PTR [rax]
,我认为这可能是因为第一个部分(eax)存储了值的地址,但是当我创建一个以char&
为参数的第三个函数时,它也创建了8字节的空间。Godbolt链接
这是有原因的吗?
英文:
In the code below,
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) };
}
Console output is
int
int
When i check the assembly code in Godbolt link.
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
reference parameter creates a space of 8 bytes QWORD PTR [rbp-8], rdi
instead of 4 bytes in second function DWORD PTR [rbp-4], edi
After seeing eax, DWORD PTR [rax]
in line 6 in firstFunction(int&):
I thought it might be because the first half(eax) stores the value adress but when i create a third function have char& as parameter it also creates 8 byte space. Godbolt Link
Is there any reason for that?
答案1
得分: 6
引用通常在底层实现时作为指针来处理,如果无法进行优化,指针在64位模式下占用8个字节。
英文:
references are usually implemented as pointers under the hood if it can't be optimized away, and pointers are 8 bytes in 64-bit mode
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论