Skip to content
Tech News
← Back to articles

Move in C++ without a std:move

read original more articles
Why This Matters

This article emphasizes the importance of leveraging return value optimization (RVO) and move semantics in C++ to enhance performance by minimizing unnecessary copy operations. Understanding when and how to use RVO and move can lead to more efficient code, especially in performance-critical applications, benefiting both developers and end-users.

Key Takeaways

In one of my earlier posts, Why you should use std::move only rarely I said that you should use std::move only rarely. In today's post, I would like to show you the benefits of this advice: best performance by default.

Return value optimization

One of the worst enemies for performance are unnecessary copy operations.

You surely heard of return value optimization (RVO). This is what you should always aim for if possible. RVO implies that the returned object isn't created on the stack inside the function but at the call-side, where the value will end up anyway. This spares you copy and move. The standard referees to this a copy elision, as the standard never talks about compiler optimizations.

You get guaranteed copy elision since C++17 in the following case:

1 2 3 4 Apple RVO () { return {}; }

This is pure RVO. Then you have named return value optimization (NRVO):

1 2 3 4 5 6 Apple NRVO () { Apple res {}; return res ; }

The latter is not subject to guaranteed copy elision. You probably don't pay for a copy or move there as well.

Move instead of copy

... continue reading