How does c++ handle memory for local variables when passing them by reference?

Viewed 77

I think I get the functionality -- passing a reference into a function passes the address, so modifications to a_val and b_val in get_point below change the values of variables in calling_func.

What I don't understand is how this is actually achieved -- are the values moved to heap space and their addresses passed into get_point? Or can addresses from the calling_func stack frame be passed into get_point and modified there?

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;
}
1 Answers

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

  • Exactly; the stack grows downwards for each function when called, and the callers stack space above is still valid when calling the callee. Usually this is achieved by passing a pointer wherever the argument would've been passed, using a lea instruction:
lea rcx, [rsp + offset to a]
lea rdx, [rsp + offset to b]
call get_point

Inside of get_point, rcx and rdx (assuming a win64 calling convention), are dereferenced and moved into xmm registers in order to operate on these variables as floating-point numbers. This is achieved for example using movss:

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

Furthermore, I suggest checking out Compiler Explorer ( https://godbolt.org/ ), if you want to see the actual assembly generated by your compiler.

Related