开发者

copy-and-swap idiom, with inheritance

开发者 https://www.devze.com 2023-04-06 12:57 出处:网络
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.

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 ???
    }
    .../...
};


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


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);
    }
    .../...
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号