我尝试了解System V AMD64 的含义-ABI的调用约定并查看以下示例:
struct Vec3{
double x, y, z;
};
struct Vec3 do_something(void);
void use(struct Vec3 * out){
*out = do_something();
}
Run Code Online (Sandbox Code Playgroud)
甲Vec3-variable是型存储器的,因此调用者(use)必须返回的变量分配空间并把它传递为隐藏指针到被叫方(即,do_something)。这是我们在生成的汇编器中看到的(在godbolt上,使用编译-O2):
use:
pushq %rbx
movq %rdi, %rbx ;remember out
subq $32, %rsp ;memory for returned object
movq %rsp, %rdi ;hidden pointer to %rdi
call do_something
movdqu (%rsp), %xmm0 ;copy memory to out
movq 16(%rsp), %rax
movups %xmm0, (%rbx)
movq %rax, 16(%rbx)
addq $32, …Run Code Online (Sandbox Code Playgroud) 我知道用C编码,函数的返回值使用%eax寄存器返回给调用者.
使用c ++,也可以返回结构而不仅仅是'Primitive'类型,所以当一个函数返回一个结构时,存储的返回值在哪里(堆栈,堆等)?
示例代码:
class Student
{
private:
int m_id;
public:
Student(int id)
{
m_id = id;
};
~Student();
int getId()
{
return m_id;
};
};
Student myFunc()
{
return Student(123);
}
int main()
{
//How does 'student1' get the value from the function?
//Does 'myFunc' write directly to the stack of main?
Student student1 = myFunc();
return 0;
}
Run Code Online (Sandbox Code Playgroud)