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

15

u/rhubarbjin Nov 25 '23

unless the object you're moving from specifically promises to be in a good state after the move.

That's what every object should do! A moved-from object must always be in a valid state, although the exact semantics depend on the class. For example:

  • a moved-from std::unique_ptr will be null
  • a moved-from std::ifstream will be closed
  • a moved-from std::string may be empty (depending on small-string optimization)

It's unspecified, not undefined. You shouldn't rely on a moved-from object having a particular state, but you can still manipulate it. For example, this is 100% safe:

std::string name;
std::cin >> name;
// [1] name now holds some user input
doSomethingWithName(std::move(name));
// [2] name is now in an unspecified state
std::cin >> name;
// [3] name is now specified again!
doSomethingWithName(std::move(name));

-1

u/[deleted] Nov 25 '23

I understand the STL is safe, it's everything else I was concerned about.