when ever a function has a object passed by value it uses either copy constructor or bit wise copy to create a temporary to place on stack to use inside the function,How about some object returned from function ?
//just a sample code to support the qn
rnObj somefunction()
{
return rnObj();
}
and also explain how the return value is taken to the called function.
As can be judged by the other answers – the compiler can optimize this.
A concrete example generated using MSVC, to explain how this is possible (as asked in one of the comments) –
Take a class –
With the following trivial implementation –
And the following calling code –
(the printf() added just to make sure the compiler doesn’t optimize everything away…).
In a non-optimized code, we would expect Func() to create a local AClass on its stack, construct it there and copy it as its return variable.
However, the generated assembly actually looks like (removing unneeded lines) –
The 3 function variables are extracted from the stack and placed into eax, ecx and edx.
Another forth value is placed into esi (and passed on to ecx).
The constructor is called with the 3 parameters on the stack, and ecx still containing the forth value.
Let’s take a look in the constructor –
The 3 constructor parameters are read into offsets of eax – eax being a copy of ecx, the forth parameter from the call above.
So, the constructor builts the object where it is told to – the forth parameter of Func().
And, you guessed it, the forth parameter of Func() is actually the real single place in the entire program where a constructed AClass exists. Let’s look at the relevant part of main() –
12 bytes are reserved for an AClass and the three arguments to Func() are passed, along with the forth one – pointing to those 12 bytes.
This is a specific example with a specific compiler. Other compilers do this differently. But that’s the spirit of things.