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;
}
The return value can be stored inside a variable at the method's call site.
Nothing. The return value is simply discarded.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
A return is a value that a function returns to the calling script or function when it completes its task.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With