Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
Darius Avatar asked Nov 16 '15 11:11

Darius


People also ask

Which member function is copy swap idiom useful for?

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.

What is a copy assignment operator?

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.


1 Answers

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.

like image 146
eerorika Avatar answered Oct 08 '22 00:10

eerorika