C++ 当你从一个函数返回一个结构体时,在汇编中实际发生了什么? [英] C++ What actually happens in assembly when you return a struct from a function?

查看:27
本文介绍了C++ 当你从一个函数返回一个结构体时,在汇编中实际发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如果你从函数中按值返回一个结构体,而不是返回一个指向该结构体的指针,那么在 C++ 中实际发生了什么.如果一个函数只能返回一个可以放入寄存器的值,那么在按值发送结构时如何进行通信?(我在某处读到过.)

I'm trying to figure out what actually happens in C++ if you return a struct by value from a function, vs. return a pointer to the struct. How is a struct communicated when its sent by value if a function can only return a value that can fit in a register? (I read that somewhere.)

我尝试在 Godbolt 上测试它,看看它在做什么.但我不了解大会,所以这对我有点乐观.

I tried testing it on Godbolt to see what it's doing. But I don't understand the assembly so that was a bit optimistic of me.

在我看来,在没有太多汇编知识的情况下,该函数只是更改了调用该函数之前存在的一些内存?因此,从函数中 return 的概念只是一个抽象,函数只是在已经存在的内存位置设置一些字节,然后结束跳转回 main()?在这种情况下,根本不复制任何内容,返回值是免费"?

It does look to me without much assembly knowledge that the function is just changing some memory that exists before the function is called? So then the concept of returning something from a function is just an abstraction and the function is just setting some bytes in a memory location that already exists and then end jumping back to main()? In which case nothing is copied at all and the return is "free"?

Godbolt:返回整数

Godbolt:返回结构{int int int}

推荐答案

所以我花了几个小时玩 Godbolt 的编译器资源管理器并阅读,直到我找到实际的答案.

So I spent hours playing with Godbolt's Compiler Explorer and reading up until I figured out the practical answer.

我收集到的是:

  1. 如果该值适合寄存器,则将其作为返回值留在寄存器中.
  2. 如果该值适合 2 个寄存器,则保留在 2 个寄存器中.
  3. 如果该值大于此值,调用方会在自己的堆栈中保留内存,函数会直接写入调用方的堆栈.

G++ 和Clang 也一样,这是在 x86_64 上测试的.

Both G++ & Clang do the same, this is tested on x86_64.

这篇关于C++ 当你从一个函数返回一个结构体时,在汇编中实际发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆