3 ms·
std::move is not only about performance. It is about being able to disallow destructive copies of certain types. I.e. unique_ptr can not be copied, and auto_ptr
by the-lazy-guy 4y ago
std::move is not only about performance. It is about being able to disallow destructive copies of certain types. I.e. unique_ptr can not be copied, and auto_ptr can. Can you write perfectly functioning code without these features? Sure! You just have to be accurate.
Same with performance. Where nowadays simple std::move() on a return value suffices you had previously explicitly to pass the object/vector with which you swapped as a parameter.
Life with move semantics is a tad easier.
- MauranKilom 4y agoNote that you don't even have to std::move a return value in almost all cases. (The very much non-language-lawyer explanation is that local variables are automatically moved from when you return them.)
- dryanau 4y agoAlso, if you write > return std::move(ret); it can interfere with return value optimisation (RVO). There might be cases where the move makes sense but to my understanding it's enough to just use return. It's very much possible to take advantage of modern C++ move semantics without an explicit call to move. Maybe you return a unique_ptr created by make_unique in a factory method, or call swap() on a moveable object, etc. I rarely need to write std::move to take advantage of modern C++ although it took some self-education about rvalues etc to learn how to do it.
- olliej 4y agoAs u/dryanau says returning std::move breaks the return value optimization such that clang at least will warn about it by default.
- the-lazy-guy 4y agoYep, you don't, as long as you want to return a local object. I know that copy elision for returns is not a permitted optimization anymory but a mandatory behavior (since C++11?). And it is a common pitfall to use unnecessary std::move calls which inhibit optimizations. But if you have something like a builder object which builds a thing which it keeps as an instance variable; then you have to use `return std::move()` or an out-parameter-and-swap if you want to avoid copies.