Re:But I was helping the compiler
by edflsafoiewq on Friday August 21, 2020 @01:17PM
(#24236871)
The version without std::move does not call a constructor because of copy elision. The get_display_pixels function constructs the disp_pixels object in place.
In the version with std::move, it first copy-elides the function call into a temporary, then move-constructs the disp_pixels object from the temporary. ie as if
auto tmp = emulator.get_display_pixels();
const auto disp_pixels = std::move(tmp); // move constructor called here
// lifetime of tmp ends
So the version with std::move is invoking an extra move-constructor and destructor call.
Re:But I was helping the compiler
by iainmerrick on Friday August 21, 2020 @02:04PM
(#24237324)
But shouldn’t those extra calls be optimized away to nothing, if they don’t have any real side-effects? That’s what I would naively assume.
Re:But I was helping the compiler
by edflsafoiewq on Friday August 21, 2020 @02:09PM
(#24237357)
I expect so, yes.
> I’m kind of surprised this is actually a literal function call, I would have assumed std::move would be always inlined
The godbolt links are without any optimization.
I think the calls to std::move in those specific examples are due to optimization flags not being passed to the compiler invocations on godbolt.
That being said, I've definitely heard of std::move in the wrong places preventing optimizations (e.g., std::move on a return statement can (will?) inhibit copy elison), but I'm not familiar enough with the finer details of C++ be able to tell you why.
Edit: I just took a look at the actual godbolt links. And it looks like the std::move version actually puts a call to std::move in the generated assembly. I’m kind of surprised this is actually a literal function call, I would have assumed std::move would be always inlined.