Search code examples
c++copy-and-swap

When is copy-and-swap idiom not applicable


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.


Solution

  • 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.