Reputation: 81
I know that coding with C, the return value of a function return to caller using %eax register.
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)?
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;
}
Upvotes: 6
Views: 339
Reputation: 60058
In C this depends on the ABI of the platform.
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.
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).
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.)
Upvotes: 9