6

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 ???
    }
    .../...
};
Community
  • 1
  • 1
gregseth
  • 12,952
  • 15
  • 63
  • 96
  • No comments on the private base-class members?? Usually a custom copy operator is implemented because there is additional handling of special cases, e.g. pointers. Such additional, crucial logic should exist outside the swap function(s), and it can also include private members. The answers only show how to handle the swap but leaves the "copy" part of the idiom unanswered. Anyone have a good pattern for the implementing the entire idiom with inheritance? – C Perkins Nov 10 '20 at 23:56

3 Answers3

11

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

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

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

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

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

You would typically be doing it like this:

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);
    }
    .../...
};
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • Except in the case where `Bar` doesn't implement a `Bar::swap(Bar &b)`. And see the link I posted about the inner/external method. – gregseth Sep 22 '11 at 13:58
  • Ok, your method was not declared static or friend, so it confused me, but I didn't read the link so that is my fault. – Vaughn Cato Sep 22 '11 at 14:32