Re:C++: Return value optimization vs. std::move
by Sirenos on Monday July 20, 2015 @11:41AM
(#9916743)
Someone correct me if I am wrong but isn't that last snippet where he returns std::move(localObj) essentially returning an rvalue-ref to a local object? That's like a big no-no because the local object destructs after foo(1) returns.
[ Parent
| on HN ]
Re:C++: Return value optimization vs. std::move
by eridius on Monday July 20, 2015 @01:07PM
(#9917397)
Presumably this is why his final output consisted of
constructor.
destructor.
move constructor
destructor.
i.e. the data destructed before it was moved.
Re:C++: Return value optimization vs. std::move
by tomjakubowski on Monday July 20, 2015 @11:50AM
(#9916827)
It'd be a problem if the function returned BigObject&&, but since it returns BigObject the move happens inside the function body which should be fine (modulo the issues raised in the article).
Re:C++: Return value optimization vs. std::move
by seabee on Monday July 20, 2015 @12:04PM
(#9916951)
In the last snippet the function returns BigObject&&.
Re:C++: Return value optimization vs. std::move
by jayrhynas on Monday July 20, 2015 @12:59PM
(#9917325)
I'm not sure if he updated the article since you read it, but he does have a note about that:
> Note: We should not use this way in the real development, because it is a reference to a local object. Here just show how to make RVO happened.
Re:C++: Return value optimization vs. std::move
by tomjakubowski on Monday July 20, 2015 @02:27PM
(#9917997)
Oh my goodness. I'll blame that one on recovering from a bad cold.
Re:C++: Return value optimization vs. std::move
by a8da6b0c91d on Monday July 20, 2015 @11:47AM
(#9916803)
It's definitely an appropriate use of std::move. When the local object destructs std::move has already ripped its guts out and put them in the object up the stack. The local object is just an empty shell at destruction.
Re:C++: Return value optimization vs. std::move
by seabee on Monday July 20, 2015 @12:02PM
(#9916941)
The 'object up the stack' is an rvalue reference. While we've successfully returned a reference into the caller's stack frame (RVO), the object it referred to has already been destroyed. That's why you see 'constructor, destructor' before 'move constructor'.
I'm struggling to see how it's an appropriate use of std::move in any case where you actually use the rvalue reference!