After reading this about the copy-and-swap idiom I've read this which says under (2):
class_name & class_name :: operator= ( const class_name & ) (2)
(2) Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used
When should we avoid using the copy-and-swap idiom ?
And when it "cannot be used" altogether?
Are there real life cases where both copy-and-swap and rule-of-zero are not applicable?
I did find this question but it was too specific and did not include any guideline as to how to identify such cases.
The copy-and-swap idiom is the solution, and elegantly assists the assignment operator in achieving two things: avoiding code duplication, and providing a strong exception guarantee.
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&. For a type to be CopyAssignable, it must have a public copy assignment operator.
When should we avoid using the copy-and-swap idiom ?
When you can prove that naïve copy is safe and faster than swap
.
You can identify the case when there are no member pointers (neither smart nor raw) that own objects and same is true for all member objects.
And when it "cannot be used" altogether?
Copy-and-swap cannot be used when the type is not swappable.
To be swappable, the type must be either move-constructible and move-assignable, or you must have defined a swap
member function or a friend function.
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