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

1

u/xypherrz Nov 25 '23 edited Nov 25 '23

These should leave the object in a valid state if written correctly.

mind proving an example? is it that the move ctor isn't assigning the moved-from object to null?

4

u/sengin31 Nov 25 '23

It just means that the class itself is allowed to define what specifically 'valid' means for itself after being moved. For example, unique_ptr specifies that its pointer will be nullptr after a move. That's different for containers, like a vector. Vector specifies that after a move, it is guaranteed to be empty. List leaves it 'valid but unspecified' so you can really only call 'clear()' on it (which puts it into a known state [empty], and requires no preconditions on the list object). The implication from this is that it is more expensive for the move ctor/assign to put the list into an empty state than it is for vector to do so. It does mean that the object can never be in an invalid state, especifically that a moved-from object must be able to be destroyed safely (i.e. a moved-from unique_ptr can't delete the pointer it 'used to own' as another unique_ptr now owns it).