Home >Backend Development >C++ >C 11: RVO or Explicit `std::move` for Return Values?
c 11 Return Value Optimization or Move?
When dealing with objects that have move semantics, programmers may wonder whether to explicitly use std::move or rely on the compiler to perform return value optimization (RVO). In cases like these:
using SerialBuffer = vector< unsigned char >; // let compiler optimize it SerialBuffer read( size_t size ) const { SerialBuffer buffer( size ); read( begin( buffer ), end( buffer ) ); // Return Value Optimization return buffer; } // explicit move SerialBuffer read( size_t size ) const { SerialBuffer buffer( size ); read( begin( buffer ), end( buffer ) ); return move( buffer ); }
which approach is preferable?
The answer is clear: always use the first method. The compiler is already capable of optimizing the return, and explicitly using std::move actually interferes with this optimization.
Copy elision allows for the use of the move constructor when returning an rvalue reference to a locally-defined variable. By explicitly moving the result, you prevent the compiler from performing this optimization for you.
Therefore, for optimal performance, stick exclusively to the first method without the explicit move. Let the compiler handle the optimization, as it is guaranteed to produce the most efficient code possible.
The above is the detailed content of C 11: RVO or Explicit `std::move` for Return Values?. For more information, please follow other related articles on the PHP Chinese website!