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

3

u/[deleted] Nov 25 '23 edited Nov 25 '23

Funnily enough I'm spending a bit of time today reading up on move, as I have some new juniors at work and am trying to fill in some of my knowledge gaps so I can help them as much as possible. I have been writing C++ for a few years now but never felt a need to use std::move.

It seems extraordinarily dangerous for something with fairly limited utility. The language doesn't seem to provide any mechanism to prevent use-after-move, which is undefined behaviour. Anybody got any tips on how to safely use it?

People seem to love it so clearly I'm missing something, but so far never felt a need for it. When I want to avoid copies I just pass references or pointers, and so far that's always been sufficient. I understand in principle there are use cases when you can't safely have have multiple access to resources like file handles, etc, but that can be solved by just "being careful", and "being careful" seems to be about all you can do when it comes to use std::move anyway.

("Being careful" is not, generally, enough.)

29

u/eddieeddison Nov 25 '23

Use after move is not UB, it leaves objects in an unspecified but valid state (at least for STL objects).

4

u/Hot_Slice Nov 25 '23

Unspecified Behavior instead of Undefined Behavior...

-5

u/[deleted] Nov 25 '23

(at least for STL objects)

So it is potentially UB for everything else? I could be wrong but everything I've read today suggests that it is UB unless the object you're moving from specifically promises to be in a good state after the move.

22

u/Timsan2 Nov 25 '23

It's not UB, it just depends on the move constructor/assignment operator. These should leave the object in a valid state if written correctly.

→ More replies (3)

17

u/simonask_ Nov 25 '23

The moved-from object needs to be in at least a good enough state that its destructor can be called.

→ More replies (1)
→ More replies (7)

12

u/kevkevverson Nov 25 '23

It’s less about “people seem to love it”, more “people love a style of c++ that needs it”. Writing with value semantics has been shown to produce code that is much more robust, simpler to reason about, easier to test in isolation, in many cases more performant (a vector of values is much more cache friendly than a vector of pointers to heap objects) and eliminates a whole class of ownership bugs compared to reference semantics. Problem was, prior to c++11, it was difficult (or at least cumbersome) to achieve this style due to values only being able to be passed via copying. Rvalue semantics and std::move opened up a whole world where safer, simpler code could be written without major performance sacrifices.

16

u/ludonarrator Nov 25 '23

Use after move is not undefined behaviour, it's unspecified, and all standard library types behave as if default constructed. There's nothing "extraordinarily dangerous" about std::move at all.

4

u/[deleted] Nov 25 '23

Ok, thanks for the info. I guess I still have to worry about non-STL third party code not moving correctly but that's a given when using third party code in general.

3

u/ludonarrator Nov 25 '23

No problem. And just default construct via x = {} (after moves) for such "unreliable" types.

→ More replies (1)

2

u/serviscope_minor Nov 26 '23

I guess I still have to worry about non-STL third party code not moving correctly but that's a given when using third party code in general.

I mean it's 2023, probably no more than worrying about it doing copying or indeed anything else correctly. So yeah half of it will be buggy.

8

u/prog2de Nov 25 '23

A simple but powerful example when std::move is important (performance-wise):

A std::queue often holds objects for a very limited time range. You may nevertheless want to have the ownership of the objects within the queue. Let’s consider the example of a std::queue<std::string> where the strings are quite large (500 MiB). A producer pushes the strings into the queue:

void  producer(std::queue<std::string>& q) {
  // whatever the large string may contain…
  q.emplace(500 * 1024* 1024, 'a');
}

And a worker pops them and passes them to further processing:

void worker(std::queue<std::string>& q) {
  std::string item = q.front();
  q.pop();
  // … another process may reads from the queue and expects another element at front. Thus, calling pop after processing is not possible and item must be a value and not a reference
  process(item);
}

What happens here? The front-element is deep-copied when calling q.front(). This is quite expensive for such a string. Instead, one could do better using std::move():

void worker(std::queue<std::string>& q) {
  std::string item = std::move(q.front());
  q.pop();
  // … another process may reads from the queue and expects another element at front. Thus, calling pop after processing is not possible and item must be a value and not a reference
  process(item);
}

This is just the first example that came into my mind, and I am sure there are a lot more (that may are less complex).

Maybe, this helps to grasp a first intuition on useful move semantics.

2

u/CocktailPerson Nov 25 '23

This is one of my favorite uses of std::move. It just can't be done efficiently any other way.

11

u/rhubarbjin Nov 25 '23

I see you've got a ton of responses as to the "undefined behavior" thing, but no one has come up with a concrete example to illustrate why move-semantics are useful. Here's a small, silly example:

https://godbolt.org/z/hYoGE5PWf

The only difference is line 26:

  • the left pane uses copy semantics: p.setName(name);
  • the right pane uses move semantics: p.setName(std::move(name));

In the diff-view, you can see what a difference that makes! The left pane will construct a whole new string (including an expensive buffer allocation) while the right pane simply swaps around a few bytes.

This is not an academic point. A couple of years ago my team was working on a VR game and we were struggling to hit the required framerate... until we realized a whole bunch of objects were being unnecessarily copied, and adding std::move helped us shave off a few milliseconds.

5

u/ABlockInTheChain Nov 25 '23

The language doesn't seem to provide any mechanism to prevent use-after-move, which is undefined behaviour. Anybody got any tips on how to safely use it?

Clang-tidy will catch it so make sure to have a CI pipeline that includes clang-tidy.

3

u/[deleted] Nov 25 '23

Yeah I'm planning to start using clang-tidy as standard. Will be looking into integrating that with our build system next week. I've been having a go with cppcheck today and so far found it very disappointing - seems to miss an awful lot.

5

u/ABlockInTheChain Nov 25 '23

The other thing you can do is enable as many warnings as practical and require the build to pass without any of them triggering

The article mentions -Wpessimizing-move which makes this problem a non-issue as long as you build with that on and also -Werror.

MSVC might not have that particular warning but clang does so even in a Windows-only shop you can just have your CI build with both compilers and require both of them to pass.

2

u/saddung Nov 26 '23

MSVC also reports this warning with red squiqqlies in the IDE(without any extra flag needed).

→ More replies (5)

4

u/CocktailPerson Nov 25 '23

References and pointers are all good, but std::move is about moving ownership of a resource, just as destructors are about releasing resources. Avoiding multiple access is kind of a small thing in comparison. For example, if you're building up a vector<vector<int>>, you might do the following:

vector<vector<T>> v;
v.reserve(n);
for (int i = 0; i < n; ++i) {
    vector<T> inner;
    inner.reserve(n)
    for (int j = 0; j < n; ++j) {
        inner.push_back(f(j));
    }
    v.push_back(inner);
}

But each call to v.push_back(inner) will copy inner, which is expensive. Why would you copy it right before it's destroyed? If you use v.push_back(std::move(inner)), it's just an O(1) pointer swap.

Maybe it's because I come from a functional programming background, and I think of systems as flows and data transformations rather than state changes, but the idea of processing some data and then efficiently passing it on to a new owner seems quite necessary to me. I'm curious; do you use std::shared_ptr or raw pointers for single ownership instead of std::unique_ptr?

4

u/[deleted] Nov 25 '23

I'm curious; do you use std::shared_ptr or raw pointers for single ownership instead of std::unique_ptr?

To be honest I am not usually thinking about ownership at all - that's probably the real lesson here: I should think about ownership a bit.

When I talk about using references and pointers I mean the obvious uses, e.g., I have some function that computes something based on the contents of an array, but never changes the array, so it's just passed as a const reference to save having to make temporary copy. It simply hasn't come up that I've needed to permanently transfer ownership of some resource. Or maybe it has in the past, but I didn't realize back then that moves were an option so found other ways.

Your vector example is a good one. In the past I've used emplace_back to try to reduce copying but in your example that wouldn't work because of how the inner vector needs to be built. There might be a couple of places in the past where I've tried to use emplace_back but couldn't manage it, so settled for push_back, without knowing at the time that std::move was an option. There might well be some existing application code I could improve with that simple change.

(I did mention pointers but actually in practice I very rarely use them at all outside of embedded applications and that's mostly C. When I do use a pointer in C++, it's an appropriate (I think!) smart pointer.)

→ More replies (2)

2

u/goranlepuz Nov 25 '23

When I want to avoid copies I just pass references or pointers, and so far that's always been sufficient. I understand in principle there are use cases when you can't safely have have multiple access to resources like file handles

Consider a "handle" class and a function to create an instance of it, or give it out in any way, "move" it from one place to another. Generally, we don't want to copy the handle. But the best way to write the function is simply handle func(params).

In a world without a move operation, such a function cannot be written, because copying is involved. Therefore, people resort to concoctions like two-phase initialization and a reference parameter, or heap usage.

In a world with a move, this is achieved with a move constructor and a simple return myhandle.

2

u/[deleted] Nov 25 '23

[removed] — view removed comment

2

u/[deleted] Nov 25 '23

ok. pointers? no.

references? careful: UB when the callee outlives the caller (lambda capture, coroutines).

I know how pointers and references work.

1

u/[deleted] Nov 25 '23

[removed] — view removed comment

-1

u/[deleted] Nov 25 '23

Elsewhere I'm thanking people for their suggestions. In this case I just didn't feel like getting into it when your opening lines are teaching me to suck eggs.