Possible Duplicate:
What is move semantics?
I recently attended a C++11 seminar and the following tidbit of advice was given.
when you have && and you are unsure, you will almost always use std::move
Could any one explain to me why you should use std::move as opposed to some alternatives and some cases when you should not use std::move?
First, there’s probably a misconception in the question I’ll address:
Whenever you see
T&& tin code (And T is an actual type, not a template type), keep in mind the value category oftis an lvalue(reference), not an rvalue(temporary) anymore. It’s very confusing. TheT&&merely means thattis constructed from an object that was an rvalue 1, buttitself is an lvalue, not an rvalue. If it has a name (in this case,t) then it’s an lvalue and won’t automatically move, but if it has no name (the result of3+4) then it is an rvalue and will automatically move into it’s result if it can. The type (in this caseT&&) has almost nothing to do with the value category of the variable (in this case, an lvalue).That being said, if you have
T&& twritten in your code, that means you have a reference to a variable that was a temporary, and it is ok to destroy if you want to. If you need to access the variable multiple times, you do not want tostd::movefrom it, or else it would lose it’s value. But the last time you acccesstit is safe tostd::moveit’s value to anotherTif you wish. (And 95% of the time, that’s what you want to do). All of this also applies toauto&&variables.1. if
Tis a template type,T&&is a forwarding reference instead, in which case you usestd::forward<T>(t)instead ofstd::move(t)the last time. See this question.