3
std::string str1{"This is a test string"};
std::string str2{std::move(str1)};
str1 = "This is a new content of this string";
// Use str1...

Am I correct thinking that str1 is in valid state now and is totally safe to use after assigning new value to it?

Alexey104
  • 969
  • 1
  • 5
  • 17
  • 3
    General form: [What can I do with a moved-from object?](https://stackoverflow.com/questions/7027523/what-can-i-do-with-a-moved-from-object) – user4581301 Dec 24 '22 at 07:11
  • 2
    Yes, it's safe (at least for the standard library classes, and for any properly designed class). – HolyBlackCat Dec 24 '22 at 07:12
  • 2
    Pulled the dupe because it was too general. There is the possibility that `string`'s assignment operator has preconditions (it doesn't), but the dupe I used doesn't cover that. Sorry about that. – user4581301 Dec 24 '22 at 07:13

2 Answers2

4

Am I correct thinking that str1 is in valid state now and is totally safe to use after assigning new value to it?

You're correct.

Is it safe to assign new value to an object that has been moved from and use this object further?

They depends on how the move operator/ constructor and the assignment operator have been defined. It can be safe (and usually is) but it can be unsafe (at least in theory).

For all standard library types (that are movable and assignable in the first place) including std::string, the move operation leaves the moved object in a valid but unspecified state and the assignment operator has no preconditions on the assigned object, so it's always allowed.

It's a good convention to provide similar guarantees for any class, but it's also possible to not do so, in which case it could be unsafe to do such assignment.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

Am I correct thinking that str1 is in valid state now and is totally safe to use after assigning new value to it?

Yes, you can safely assign to str1(as you've done) and then use str1 for further purposes.

Jason
  • 36,170
  • 5
  • 26
  • 60