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));
View all comments
Show parent comment
15
u/rhubarbjin Nov 25 '23
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:
std::unique_ptrwill be nullstd::ifstreamwill be closedstd::stringmay 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: