I\'m trying to understand rvalue references and move semantics of C++11.
What is the difference between these examples, and which of them is going to do no vector cop
Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&&
variable (as you did with std::vector
). You will still have to std::move()
them to use in foo(T&&)
type methods. There is also the problem that was already mentioned that when you try to return such rval_ref
from function you will get the standard reference-to-destroyed-temporary-fiasco.
Most of the time I would go with following pattern:
// Declarations
A a(B&&, C&&);
B b();
C c();
auto ret = a(b(), c());
You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.
auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));
// Either these just fail (assert/exception), or you won't get
// your expected results due to their clean state.
bRet.foo();
cRet.bar();
Obviously there are (although rather rare) cases where a function truly returns a T&&
which is a reference to a non-temporary object that you can move into your object.
Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if
conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).