My understanding is that C++ implicitly generated assignment operator does a member-wise copy (this seems confirmed also by this answer). But, if during a member copy an exception is thrown (e.g. because a resource for that member can't be allocated), will the object being copied be stuck in an invalid state?
In other words, does the implicitly generated assignment operator achieve only the basic guarantee, but not the strong guarantee?
If we want the strong guarantee for our class copies, must we implement the assignment operator manually with the copy-and-swap idiom?
If you want to offer an exception guarantee, and the default assignment operator is not nothrow then normally you need to write one.
The default copy assignment doesn't necessarily achieve even the basic guarantee, which is that no resources are leaked and the class invariants are preserved. Assigning some of the data members but not all might leave the target in a state where class invariants are not satisfied, depending on the particular class.
So you have to assess the default operator for your class -- if it can throw, and by throwing leave the object in an "invalid" state, then you have to suppress it. Or weaken the defined class invariants, but that's not very helpful to users.
There is (at least) one special case. If all the data members except for one have nothrow assignment, and the special one has strongly exception-safe assignment, and is the first data member in the class, then the default assignment operator would also be strongly safe. You might want to comment that quite carefully if you're relying on it, though, it could prove to be quite fragile!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With