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

2

5
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?

Auberbach answered 24/12, 2022 at 6:59 Comment(3)
General form: What can I do with a moved-from object?Highline
Yes, it's safe (at least for the standard library classes, and for any properly designed class).Fortyniner
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.Highline
B
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.

Biathlon answered 24/12, 2022 at 7:16 Comment(0)
M
5

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.

Manofwar answered 24/12, 2022 at 13:7 Comment(0)
B
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.

Biathlon answered 24/12, 2022 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.