Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy-and-swap idiom, with inheritance

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 ???
    }
    .../...
};
like image 760
gregseth Avatar asked Sep 22 '11 13:09

gregseth


People also ask

What is copy and swap idiom?

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.

How does STD swap work?

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.


2 Answers

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

like image 199
Mike Seymour Avatar answered Sep 23 '22 08:09

Mike Seymour


Just cast it up to the base and let the compiler work it out:

swap(static_cast<Bar&>(a), static_cast<Bar&)(b));

like image 21
Mark B Avatar answered Sep 20 '22 08:09

Mark B