存储的返回值在哪里?

时间:2018-05-30 09:14:06

标签: c++ c

我知道用C编码,函数的返回值使用%eax寄存器返回调用者。

使用c ++也可以返回结构而不仅仅是' Primitive'类型,所以当一个函数返回一个struct时,返回的值存储在哪里(堆栈,堆等)?

示例代码:

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

1 个答案:

答案 0 :(得分:8)

在C中,这取决于平台的ABI。

x86_64 linux上,有几类数据类型,但简单来说,在寄存器中返回小的简单结构(〜< = 2 longs),在堆栈中返回大的结构。

最新的C ++应该保证RVO(返回值优化)我相信,这意味着结构/类应该在调用者的堆栈上分配,并且被调用者应该通过指针“秘密”写入它们(C ABIs /编译器可以这样做,但在C ++中,RVO还避免了破坏和复制构造。

您可以随时查看程序集或编写基准来验证传递约定。

(在我看来,最好将自己限制在C中的简单返回类型,这样你就不用担心了。(原始C甚至不允许返回结构。)在带有RVO的C ++中没关系。)

相关问题