C++函数返回在堆栈上创建的对象

C++ Function returning object created on the stack

本文关键字:创建 对象 堆栈 函数 返回 C++      更新时间:2023-10-16

我知道当我使用__stdcall时(对于其他调用约定也是如此),返回的值存储在eax寄存器中。我想知道以下情况是如何发生的:

class MyObject
{
private:
    int fourBytesInt;
    long fourBytesLong;
    char name[256];
};
MyObject ReturnMe()
{
    MyObject myObj = MyObject();
    return myObj;
}
int main(void)
{
    MyObject myObj = ReturnMe();
    return 0;
}

sizeof(myObj)是264字节,ReturnMe函数怎么会返回这么大的对象,因为寄存器最多可以容纳32位(x86架构)。

谢谢!

返回值只放在足够小的数据类型的寄存器中。否则,它们将作为堆栈上的副本返回。或者有时可以省略副本。