【问题标题】:copy-and-swap idiom, with inheritance复制和交换习语,具有继承性
【发布时间】:2011-11-22 20:34:15
【问题描述】:

我阅读了interesting things 关于复制和交换习语的内容。我的问题是关于从另一个类继承时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 ???
    }
    .../...
};

【问题讨论】:

  • 私有基类成员上没有 cmets??通常会实现自定义复制操作符,因为有特殊情况的额外处理,例如指针。这种额外的、关键的逻辑应该存在于交换函数之外,它也可以包括私有成员。答案只显示了如何处理交换,但没有回答成语的“复制”部分。任何人都有一个很好的模式来实现整个成语的继承?

标签: c++ inheritance idioms


【解决方案1】:

你可以交换子对象:

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

如果std::swap 不起作用,您可能需要为Bar 实现交换功能。另请注意,swap 应为非会员(必要时为朋友)。

【讨论】:

  • 为避免强制转换,您可以执行 "Bar &a_bar = a, &b_bar = b; swap(a_bar,b_bar);"
【解决方案2】:

只需将其转换为基础并让编译器解决:

swap(static_cast&lt;Bar&amp;&gt;(a), static_cast&lt;Bar&amp;)(b));

【讨论】:

    【解决方案3】:

    你通常会这样做:

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

    【讨论】:

    • 除非Bar 没有实现Bar::swap(Bar &amp;b)。并查看我发布的有关内部/外部方法的链接。
    • 好的,你的方法没有声明为静态或友元,所以我很困惑,但我没有阅读链接,所以这是我的错。
    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2014-06-23
    • 2012-10-06
    • 2020-05-27
    • 2016-02-17
    • 2013-08-10
    相关资源
    最近更新 更多