Idiom with copy and replace, with inheritance

I read interesting things about the copy and swap idiom. My question is about implementing a method swapwhen 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 ???
    }
    .../...
};
+5
source share
3 answers

You would replace the subobjects:

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

You may need to implement the swap function for Barif you are std::swapnot completing the task. Also note that it swapmust be non-member (and if necessary a friend).

+9
source

Just drop it to the base and let the compiler understand:

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

+2
source

:

class Foo : public Bar
{
    int _m1;
    string _m2;
    .../...
public:
    void swap(Foo &b)
    {
         using std::swap;

         swap(_m1, b._m1);
         swap(_m2, b._m2);
         Bar::swap(b);
    }
    .../...
};
0

All Articles