First examplestd::vector
return_vector(void){ std::vector
tmp {1,2,3,4,5}; return tmp;}std::vector
&&rval_ref = return_vector();
The first example returns a temporary which is caughtrval_ref . That temporary will have its life extended beyondrval_ref Definition and you can use it as if you had caught it by value. This is very similar to the following: const std::vector
& rval_ref = return_vector();
Could t that in my rewrite you obviusly can't use rval_ref in a non-const manner. Second examplestd::vector
&& return_vector(void){ std::vector
tmp {1,2,3,4,5}; return std::move(tmp);}std::vector
&&rval_ref = return_vector();
In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code wowould immediately crash. Third examplestd::vector
return_vector(void){ std::vector
tmp {1,2,3,4,5}; return std::move(tmp);}std::vector
&&rval_ref = return_vector();
Your third example is roughly equivalent to your first. The std: move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization. The best way to code what you're doing is: Best practicestd::vector
return_vector(void){ std::vector
tmp {1,2,3,4,5}; return tmp;}std::vector
rval_ref = return_vector();
I. e. just as you wocould in C ++ 03. tmp is implicitly treated as an rvalue in the return statement. it will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. only if RVO is not saved med, and if the returned type did not have a move constructor wocould the copy constructor be used for the return.
Shareeditflag |
Answered Feb 13 '11 at 20: 52 Howard Hinnant 74.1k12145133 |
|