The inherent value of a copy-swap pattern for the operator =
in a C++ data container is said to arise from
However the copy-swap idiom allocates much more memory than would otherwise be necessary, as data is not destroyed before the copy is created, increasing the chance of exceptions substantially. Given that this is the case, what is the point in claiming that it is a useful pattern?
Are there any other cases in which a copy operation could throw (that do not relate to the objects being copied) other than running out of memory?
The copy&swap idiom for the assignment operator yields the strong exception guarantee: the original value is untouched when building a new object would throw. When reusing memory allocated for the assigned to object the strong exception guarantee can typically only be achieved when none of the involved operation may throw. Especially when class templates are involved (as in std::vector<T>
) there is generally no guarantee that none of the operations throws (of course, std::vector<T>
only provides the basic exception guarantee upon assignment).
In general, copy assignments can throw for whatever reason. Most likely they shouldn't throw for other reasons than failures to allocate resources but there isn't anything in the CopyAssignable concept which prohibits the operation from throwing.
I found it quite common that copy assignments were not correctly implemented and would, e.g., violate the basic exception guarantee. The indicator that this is the case is when the assignment operator needs to check for self-assignment: if a self-assignment is actually needed (rather than just being there, sometimes defined as an "optimization" - how often do people do self-assignments...?), the code is almost certainly wrong, most likely not maintaining the basic exception guarantee. As a result I recommend using the copy&swap approach unless there is a very good reason not to although I'm aware that it uses more memory (although the problem is rarely that there isn't enough memory, at least not on the systems I'm working on, but rather that use of more memory may result in slower execution).
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