3 ms·
> Returning a stack allocated value does not invoke the move constructor. Unless the 'named return value' you're returning happens to be a named parameter. Ex
by nly 10y ago
> Returning a stack allocated value does not invoke the move constructor.
Unless the 'named return value' you're returning happens to be a named parameter.
Example: https://ideone.com/TddXn7 https://ideone.com/TddXn7
The move here actually comes from the return, not passing in the newly constructed object. The compiler is eliding Foo's move constructor in main(), but it can't elide both... even if the function is fully inlined.
- banachtarski 10y agoYes good point. NRVO doesn't apply here and named parameters are in fact moved or copied depending on if they are passed by value or by reference. In your case a move would happen but if you changed the parameter to a reference I think it would copy.
- nly 10y agoYes it would copy, unless you used an explicit std::move(). This is why most of the time you're better off just passing things around by value, and making your classes cheap to move (by, force example, making use of pointers (smart or otherwise)). This results in less code and more manageable semantics.