I have a class
class MyClass
{
public :
int a;
int b;
}
For using the copy-swap idiom I then create the function
void MyClass::swap(MyClass& other)
{
std::swap(a,other.a);
std::swap(b,other.b);
}
If, later, I change my class and remove the member a
, then the compiler will complain in the swap
function, and that's fine.
But if I add a new member, my swap
function is not correct anymore. What can I do in order to not forget adding the new member to the swap function ?
The problem is that your answer is not the copy and swap idiom. The actual copy and swap idiom is to write the copy constructor, and move operations for the class. The latter will give you an efficient swap operation via std::swap. Then you write your copy assignment by calling your class copy constructor to create a local copy. Then swap *this with the temporary. You don't do it member by member.
The best way to not forget is to just not write any of the special member functions, and have the compiler generate them for you. This is called the rule of zero. Most classes should not need to write these methods but simply choose members (or write them) such that the generated ones are correct. One of the reasons being no extra maintenance when adding a member.
Finally, if you are writing a resource management class and are writing these functions by hand, you don't necessarily want to use copy and swap. Copy and swap basically trades performance for strong exception safety. I've almost never made use of strong exception safety and in many domains it's just not practical to write things this way. So only use it if you need it.