Home > Back-end >  Is it safe to assign new value to an object that has been moved from and use this object further?
Is it safe to assign new value to an object that has been moved from and use this object further?

Time:12-24

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related