我想我得到了功能-将引用传递给函数会传递地址,因此,下面对a_val中的b_valget_point的修改会更改calling_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;
}

最佳答案

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]
    
    此外,如果您想查看由编译器生成的实际程序集,建议您 check out Compiler Explorer(https://godbolt.org/)。

    关于c++ - 当通过引用传递局部变量时,c++如何处理局部变量的内存?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63538556/

    10-11 22:16
    查看更多