Return Value Optimization vs. Explicit Move in C 11: Which to Use?
In C 11, developers have the option to enhance performance through two techniques: Return Value Optimization (RVO) and explicit move operations using std::move. When considering which approach to use, it's essential to understand the differences and their respective applicability.
Return Value Optimization (RVO)
RVO is an optimization technique implemented by the compiler that eliminates unnecessary copying operations. When the return statement of a function involves an object whose lifetime ends immediately after the function's execution, the compiler may optimize the copy by returning the object's value directly, thus avoiding its construction and destruction.
Explicit Move Operation
An explicit move operation using std::move forces the compiler to move the ownership of an object instead of copying it. This is achieved by passing the object as an rvalue reference and then invoking std::move on its return value.
Which Approach to Use?
When selecting between RVO and explicit move, always prioritize the use of RVO. Copy elision is a highly effective compiler optimization that can significantly improve performance.
As demonstrated in the code snippet provided, the function read can return a SerialBuffer using RVO:
SerialBuffer read(size_t size) const { SerialBuffer buffer(size); read(begin(buffer), end(buffer)); return buffer; }
By default, the compiler will optimize the return operation, eliminating the need for copying if possible.
Explicit move operations should only be used when RVO cannot be applied. For example, if the object's lifetime extends beyond the execution of the function, using std::move can explicitly signal the intent to move ownership of the object. However, this should be a rare scenario, and RVO should generally suffice.
The above is the detailed content of RVO vs. Explicit Move in C 11: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!