On 10/31/2014 1:03 PM,
porp...@gmail.com wrote:
> I found that returning from my_fun is costless. None of the constructors or assignment operator of Human is called.
> I expect the non-default constructor of Human to be called as the result of "return value optimization".
> Why is that ?
Why is what? Why is it that you expect the non-default c-tor of Human
to be called? I don't know. Why do you?
RVO allows the compiler to eliminate copying from the value in the
'return' expression in some function whose body the compiler can see,
when that value is used to initialize another object of the same type.
blah func_returning_a_blah()
{
...
return some_blah;
}
...
blah b = func_returning_a_blah(); // no copying due to RVO
If the compiler can see the function, it will inline the code in such a
way so it initialized the 'some_blah' directly into 'b'.
Costless, yes. What's the big deal?
As an experiment, move 'my_fun' function definition to a separate
translation unit, and you *might* see a copy made, depending on how
clever your compiler is. However, often the compiler can create a
hidden "argument" for a value-returning function for the return value
(since it is needed by the caller anyway), and in the case of the
initialization, the address of the object being initialized is going to
be used as that hidden "argument", so even after moving the function so
it can't be inlined any longer, you are still going to see no copy made.
> return 0;
> }
>
> thanks for clarification
>
V
--
I do not respond to top-posted replies, please don't ask