Rvalue References and Move Semantics in C 11 Unraveled
In C 11, rvalue references and move semantics provide powerful techniques for improving performance and efficiency. This article explores the nuances of these concepts through a detailed analysis of three examples:
First Example:
std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> &&rval_ref = return_vector();
In this example, the function return_vector returns a temporary vector object by value. The rvalue reference rval_ref binds to this temporary object. The temporary object's lifetime is extended beyond the function call, allowing rval_ref to continue accessing its data. However, any modifications made through rval_ref will not affect the original vector.
Second Example:
std::vector<int>&& return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp); } std::vector<int> &&rval_ref = return_vector();
This example is flawed due to a runtime error. The function return_vector uses std::move on the temporary vector tmp before returning it. This effectively destroys tmp and leaves rval_ref holding a reference to invalid memory. Consequently, this code may crash upon execution.
Third Example:
std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp); } std::vector<int> &&rval_ref = return_vector();
Similar to the first example, this example uses std::move on the temporary vector tmp before returning it by value. However, since the function already returns by value, the std::move is redundant and may be a performance penalty due to additional memory operations.
Best Practice:
The preferred way to write this code is to omit the unnecessary std::move and rely on C 11's implicit conversion of rvalues in return statements:
std::vector<int> return_vector(void) { std::vector<int> tmp {1,2,3,4,5}; return tmp; } std::vector<int> rval_ref = return_vector();
In this case, the compiler will optimize the return using return value optimization (RVO) to eliminate unnecessary copying or moving. Alternatively, if RVO is not feasible, the compiler will use the move constructor of the vector class to perform an efficient transfer of ownership.
The above is the detailed content of How Do Rvalue References and Move Semantics Improve C 11 Performance?. For more information, please follow other related articles on the PHP Chinese website!