复制和交换习语,带继承

gre*_*eth 6 c++ inheritance idioms

我读了有关复制和交换习语的有趣信息.我的问题是关于swap从另一个类继承时该方法的实现.

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 ???
    }
    .../...
};
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 11

你会交换子对象:

swap(static_cast<Bar&>(a), static_cast<Bar&>(b));
Run Code Online (Sandbox Code Playgroud)

Bar如果std::swap不执行此任务,您可能需要实现交换功能.另请注意,swap应该是非会员(如果需要,还可以是朋友).