So I have been reading about std::move
, std::forward
, rvalues, lvalues ad so on in SO and other places. But I find that I can't grasp it. Even though I sometimes get into fixes, I think I understand basic stuff about pointers, references, etc which were in C++ before all this. Is it me or are these stuff getting too heavy?
I would recommend reading the original proposal if you haven't already:
A Proposal to Add Move Semantics Support to the C++ Language
It lays out very clearly the problems that can be solved with rvalue references and move semantics and how rvalue references and move semantics can be used to solve those problems.
Standards committee papers are often dense and difficult to understand, but this one is quite accessible and very much worth reading. The rvalue references and move semantics as specified in the final C++0x standard (whenever that happens) may be different from what is proposed in this paper, but the concepts are still the same.
Your question is very general. Maybe I can get you started:
std:move()
and std::forward()
at the beginningMatrix z = a + b + c + d;
(with Matrix a,b,c,d;
)operator+
on Matrix
with overloaded RValue References.If you want to see a simple use of std::move()
: Help the compiler to avoid introducing a copy for a return value:
Image
-- costly to copy.invent a factory function that works like this:
Image load_matching_size(const char *fn_small, const char *fn_big) { pair<Image> ii = load_2_images(fn_small, fn_big); return ii.first.width() >= 64 ? ii.first : ii.second; }
Can you count the numbers of temporaries? Note that the return
will need an additional one and copy! (The example is designed so that return-value-optimization ("RVO") should not be possible)
ii
will be thrown away shorty after the function returned. Could the compiler use then for the return value? (No it could not. RVO would work if we had only one Image
).move
in the return
you can tell the compiler, that you do not need ii
further and that it can use it for the return. And thus spare a costly copy my using the move-c'tor instead of the copy-c'tor for the return.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With