I read interesting things about the copy-and-swap idiom. My question is concerning the implementation of the swap
method when inheriting from another class.
class Foo : public Bar
{
int _m1;
string _m2;
.../...
public:
void swap(Foo &a, Foo &b)
{
using std::swap;
swap(a._m1, b._m1);
swap(a._m2, b._m2);
// what about the Bar private members ???
}
.../...
};
Copy-and-Swap Idiom in C++ But when overloading the assignment operator, it can become quite difficult to implement. The copy and swap idiom is a solution for the same. This idiom uses the copy-constructor to build a local copy of the data. It then swaps the old data with the new data using the swap function.
The std::swap() function is a built-in function in the C++ STL. The swap(T& a, T& b) function calls by reference and the C++ overloads swap( ) function based on the data types of the variables passes, if the variables pass of different data types the swap( ) function throw error or exception.
You would swap the subobjects:
swap(static_cast<Bar&>(a), static_cast<Bar&>(b));
You may need to implement the swap function for Bar
, if std::swap
doesn't do the job. Also note that swap
should be a non-member (and a friend if necessary).
Just cast it up to the base and let the compiler work it out:
swap(static_cast<Bar&>(a), static_cast<Bar&)(b));
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