首页 > 解决方案 > c++ 在通过引用传递局部变量时如何处理它们的内存?

问题描述

我想我得到了这个功能——将引用传递给函数会传递地址,因此对a_val和下面的修改b_val会改变.get_pointcalling_func

我不明白这实际上是如何实现的——这些值是否移动到堆空间并将它们的地址传递到get_point?或者可以将calling_func堆栈帧中的地址传递到get_point那里并在那里修改?

void calling_func() {
    float a, b;
    get_point(a,b);
}
void get_point(float& a_val, float& b_val) {
    a_val = 5.5;
    b_val = 6.6;
}

标签: c++memorycompilation

解决方案


Or can addresses from the calling_func stack frame be passed into get_point and modified there?

  • 确切地; 每个函数调用时栈向下增长,调用者调用被调用者时,上面的调用者栈空间仍然有效。通常这是通过使用lea指令将指针传递到参数将被传递的任何位置来实现的:
lea rcx, [rsp + offset to a]
lea rdx, [rsp + offset to b]
call get_point

在内部get_point,rcx 和 rdx(假设是 win64 调用约定)被取消引用并移动到 xmm 寄存器中,以便将这些变量作为浮点数进行操作。这是通过例如使用来实现的movss

movss xmm0, [rcx]  // this is where the actual dereferencing of the references in question happens
movss xmm1, [rdx]

此外,如果您想查看编译器生成的实际程序集,我建议您查看编译器资源管理器 ( https://godbolt.org/ )。


推荐阅读