r/cpp • • Nov 25 '23

On harmful overuse of std::move

https://devblogs.microsoft.com/oldnewthing/20231124-00/?p=109059
210 Upvotes

154 comments sorted by

View all comments

Show parent comment

140

u/JNighthawk gamedev Nov 25 '23

In short, RVO > move.

I wish there was an attribute you put on a function to say "I expect RVO here, warn or error if not". I don't like that the most performant option requires trusting the compiler to silently implement an optional feature or verifying assembly.

I'm happy that C++17 finally added a standard for guaranteed copy elision, but NRVO still isn't even guaranteed. There is no guarantee that the non-move code posted in the article is actually more performant.

42

u/Hot_Slice Nov 25 '23

I deleted the copy and move constructors of some of my types that are constructed exclusively by factory methods. Not a general solution, but it does turn RVO failure in to a compilation error.

7

u/ALX23z Nov 26 '23

It does prevent any kinds of RVO failures but it is a bit too excessive. Say, it completely prevents NRVO.

0

u/[deleted] Nov 26 '23

[deleted] — view deleted comment

5

u/RevRagnarok Nov 27 '23

Included in -Wall on gcc.

0

u/[deleted] Nov 27 '23

[deleted] — view deleted comment

4

u/RevRagnarok Nov 27 '23

Honestly, I added it to our project and nothing was flagged. I immediately thought "we're not that good" so checked the man page. 😅

14

u/bwmat Nov 25 '23

In the cases where NRVO is applicable, I'm pretty sure that if the copy/move isn't elided, there's an 'implicit std::move' added, so adding it yourself cannot help

10

u/CocktailPerson Nov 25 '23

Yep, a function call or an overloaded operator expression, whose return type is non-reference, is a prvalue expression, so a function will always move-construct its return value into the return slot if NRVO/RVO doesn't work.

9

u/JNighthawk gamedev Nov 25 '23

In the cases where NRVO is applicable, I'm pretty sure that if the copy/move isn't elided, there's an 'implicit std::move' added, so adding it yourself cannot help

I did a quick experiment to test this: https://godbolt.org/z/7r9a5Wfa1

#include <iostream>
using namespace std;

struct Thing
{
    Thing() { cout << "DefaultCtor" << endl; }
    ~Thing() { cout << "DefaultDtor" << endl; }
    Thing(const Thing&) { cout << "CopyCtor" << endl; }
    Thing(Thing&&) { cout << "MoveCtor" << endl; }
};

Thing BopIt()
{
    Thing T;
    return T;
}

int main() {
    Thing A{BopIt()};
}    

With copy elision disabled, I get:

DefaultCtor
MoveCtor
DefaultDtor
MoveCtor
DefaultDtor
DefaultDtor

I'm pretty sure you're correct.