简体   繁体   English

存储的返回值在哪里?

[英]Where are returned values stored?

I know that coding with C, the return value of a function return to caller using %eax register. 我知道用C编码,函数的返回值使用%eax寄存器返回给调用者。

With c++ it is also possible to return structs and not just 'Primitive' types, so when a function returns a struct, where is the returned value stored (stack, heap, etc)? 使用c ++,也可以返回结构而不仅仅是'Primitive'类型,所以当一个函数返回一个结构时,存储的返回值在哪里(堆栈,堆等)?

Example Code: 示例代码:

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

In C this depends on the ABI of the platform. 在C中,这取决于平台的ABI。

On x86_64 linux , there are several classes of data types but in simple terms, small simple structs (~ <= 2 longs) are returned in registers and large ones through the stack. x86_64 linux上 ,有几类数据类型,但简单来说,在寄存器中返回小的简单结构(〜<= 2 longs),在堆栈中返回大的结构。

The latest C++ should guarantee RVO (Return Value Optimization) I believe, which means structs/classes should get allocated on the stack in the caller and the callee should "secretly" write to them via a pointer (C ABIs/compilers can do this too, but in C++, RVO additionally avoids destruction and copy-construction). 最新的C ++应该保证RVO(返回值优化)我相信,这意味着结构/类应该在调用者的堆栈中分配,并且被调用者应该通过指针“秘密”写入它们(C ABIs /编译器也可以这样做,但在C ++中,RVO还避免了破坏和复制构造)。

You can always look at the assembly or write a benchmark to verify the passing convention. 您始终可以查看程序集或编写基准来验证传递约定。

(In my opinion, it is, however, best to limit oneself to simple return types in C so you don't have to worry. (Original C didn't even allow one to return structs.) In C++ with RVO it shouldn't matter.) (在我看来,最好将自己限制在C中的简单返回类型中,这样你就不用担心了。(原始C甚至不允许返回结构。)在使用RVO的C ++中,它不应该'无所谓。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM