// HACKER NEWS — CYBERSECURITY
Move in C++ without a std:move
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.
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:
This is pure RVO. Then you have named return value optimization (NRVO):
The latter is not subject to guaranteed copy elision. You probably don't pay for a copy or move there as well.
The next best thing after copy elision is moving an object. The language had a few places where implicit moves happened since C++11:
In this code, the resulting object is moved from the parameter.
But we had cases in the language where things have been a bit more complicated.
You have a function that takes a rvalue reference parameter and returns the just received object. While this code compiles, you will get a copy construction of the return value before C++20. Well, with a conforming compiler like GCC. The less-conforming compiler Clang gives you a move construction. Yes, sometimes not playing by the book can be better.