c++ - c++ 在通过引用传递局部变量时如何处理它们的内存?
问题描述
我想我得到了这个功能——将引用传递给函数会传递地址,因此对a_val
和下面的修改b_val
会改变.get_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]
此外,如果您想查看编译器生成的实际程序集,我建议您查看编译器资源管理器 ( https://godbolt.org/ )。
推荐阅读
- mysql - 错误:无法在只读事务中执行语句
- r - 匹配/替换对应于R中不同数据框的多个数据框列
- plesk - Plesk - 没有域的 http 访问 - 永远使用 plesk-site-preview?
- c# - 如何实现像进入地牢一样的旋转武器?
- mysql - 当两个表中都不存在数据时查询不返回结果
- android-studio - 如何安装已经在后台下载的android studio sdk包?
- javascript - 如何指示一个对象在打字稿中可能没有键
- php - 如何将参数传递给 PDO 准备语句
- spring-boot - 如何使用注释将 3 个类相互连接?(JPA/Spring-Boot)
- docker - Vagrant + Docker 提供商,在静态 IP 上苦苦挣扎