在副本和交换习语

时间:2016-03-15 12:03:24

标签: c++ c++11 copy-constructor assignment-operator copy-and-swap

What is the copy and swap idiomHow to provide a swap function for my class之后,我尝试实现交换功能,就像后面接受的答案选项2(具有调用成员函数的自由函数)而不是直接友好的自由函数前一个链接。

但是以下内容并没有编译

#include <iostream>

// Uncommenting the following two lines won't change the state of affairs
// class Bar;
// void swap(Bar &, Bar &);
class Bar {
public:
  Bar(unsigned int bottles=0) : bottles(bottles) { enforce(); } // (1)
  Bar(Bar const & b) : bottles(b.bottles) { enforce(); } // (1)

  Bar & operator=(Bar const & b) {
    // bottles = b.bottles;
    // enforce();
    // Copy and swap idiom (maybe overkill in this example)
    Bar tmp(b); // but apart from resource management it allows (1)
                // to enforce a constraint on the internal state
    swap(*this, tmp); // Can't see the swap non-member function (2)
    return *this;
  }

  void swap(Bar & that) {
    using std::swap;
    swap(bottles, that.bottles);
  }

  friend std::ostream & operator<<(std::ostream & out, Bar const & b) {
    out << b.bottles << " bottles";
    return out;
  }

private:
  unsigned int bottles;
  void enforce() { bottles /=2; bottles *= 2; } // (1) -- Ensure the number of bottles is even
};

void swap(Bar & man, Bar & woman) { // (2)
  man.swap(woman);
}

int main () {
  Bar man (5);
  Bar woman;

  std::cout << "Before -> m: " << man << " / w: " << woman << std::endl;
  swap(man, woman);
  std::cout << "After  -> m: " << man << " / w: " << woman << std::endl;

  return 0;
}

我知道复制和交换习惯在这里是过度的,但它也允许通过复制构造函数(1)对内部状态强制执行某些约束(更具体的例子是以缩减形式维护一个分数)。不幸的是,这并没有编译,因为编译器看到的(2)的唯一候选者是Bar :: swap成员函数。我是否坚持使用朋友非会员功能方法?

编辑:转到my answer below,看看我最终得到了什么,感谢关于这个问题的所有答案和评论。

5 个答案:

答案 0 :(得分:5)

我认为我们发布了c ++ 11?

在这种情况下,std :: swap的默认实现将是最优的,前提是我们正确实现了move-assignment操作符和move-constructor(理想情况下是nothrow)

http://en.cppreference.com/w/cpp/algorithm/swap

#include <iostream>

class Bar {
public:
    Bar(unsigned int bottles=0) : bottles(bottles) { enforce(); } // (1)
    Bar(Bar const & b) : bottles(b.bottles) {
        // b has already been enforced. is enforce necessary here?
        enforce();
    } // (1)
    Bar(Bar&& b) noexcept
    : bottles(std::move(b.bottles))
    {
        // no need to enforce() because b will have already been enforced;
    }

    Bar& operator=(Bar&& b) noexcept
    {
        auto tmp = std::move(b);
        swap(tmp);
        return *this;
    }

    Bar & operator=(Bar const & b)
    {
        Bar tmp(b); // but apart from resource management it allows (1)
        swap(tmp);
        return *this;
    }

    void swap(Bar & that) noexcept {
        using std::swap;
        swap(bottles, that.bottles);
    }

    friend std::ostream & operator<<(std::ostream & out, Bar const & b) {
        out << b.bottles << " bottles";
        return out;
    }

private:
    unsigned int bottles;
    void enforce() {  } // (1)
};

/* not needed anymore
void swap(Bar & man, Bar & woman) { // (2)
    man.swap(woman);
}
*/
int main () {
    Bar man (5);
    Bar woman;

    std::cout << "Before -> m: " << man << " / w: " << woman << std::endl;
    using std::swap;
    swap(man, woman);
    std::cout << "After  -> m: " << man << " / w: " << woman << std::endl;

    return 0;
}

预期结果:

Before -> m: 5 bottles / w: 0 bottles
After  -> m: 0 bottles / w: 5 bottles

编辑:

为了任何关心表演的人(例如@JosephThompson)的利益,请允许我减轻您的担忧。将调用移动到std::swap到一个虚函数(强制clang生成任何代码),然后使用带有-O2的apple clang进行编译,这个:

void doit(Bar& l, Bar& r) override {
    std::swap(l, r);
}

成了这个:

__ZN8swapper24doitER3BarS1_:            ## @_ZN8swapper24doitER3BarS1_
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp85:
    .cfi_def_cfa_offset 16
Ltmp86:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp87:
    .cfi_def_cfa_register %rbp
    movl    (%rsi), %eax
    movl    (%rdx), %ecx
    movl    %ecx, (%rsi)
    movl    %eax, (%rdx)
    popq    %rbp
    retq
    .cfi_endproc 

请参阅?最佳。 c ++标准库摇滚!

答案 1 :(得分:4)

注意:这是使用copy和swap之前的C ++ 11方式。对于C ++ 11解决方案,请参阅this answer

为了让这个工作,你需要解决一些问题。首先,您需要转发声明交换自由函数,以便operator=知道它。为了做到这一点,您还需要转发声明Bar以便swap有一个名为bar的类型

class Bar;

void swap(Bar & man, Bar & woman);

// rest of code

然后我们需要告诉编译器在哪里寻找swap。我们这样做的方法是使用范围解析运算符。这将告诉编译器查看类swap函数

的范围
Bar & operator=(Bar const & b) {
  // bottles = b.bottles;
  // enforce();
  // Copy and swap idiom (maybe overkill in this example)
  Bar tmp(b); // but apart from resource management it allows (1)
            // to enforce a constraint on the internal state
  ::swap(*this, tmp); // Can't see the swap non-member function (2)
//^^ scope operator 
  return *this;
}

我们把所有这些放在一起,我们得到了这个Live Example

实际上,副本operator =应该看起来像

Bar & operator=(Bar b) // makes copy
{
    ::swap(*this, b) // swap the copy
    return *this; // return the new value
}

答案 2 :(得分:1)

您知道Bar具有swap成员函数,因此请直接调用它。

Bar& operator=(Bar const& b) {
    Bar tmp(b);
    tmp.swap(*this);
    return *this;
}

非成员swap仅存在,以便Bar的客户可以利用其优化的swap实施,而无需知道它是否存在,使用using std::swap成语来启用argument-dependent lookup

using std::swap;
swap(a, b);

答案 3 :(得分:0)

您还需要在该功能中启用std::swap

using std::swap;
swap(*this, tmp); // Can't see the swap non-member function (2)

引用answer you referred

  

如果现在使用swap,如1)所示,将找到您的功能。

使用方式:

{
  using std::swap; // enable 'std::swap' to be found
                   // if no other 'swap' is found through ADL
  // some code ...
  swap(lhs, rhs); // unqualified call, uses ADL and finds a fitting 'swap'
                  // or falls back on 'std::swap'
  // more code ...
}

Live on Coliru

答案 4 :(得分:0)

对于上面的上下文,只需要强制执行一些内部约束,最好使用默认值,并且只在直接初始化构造函数中强制执行一次。如果你需要实现这些功能,请查看@RichardHodges的答案!另请参阅@HowardHinnant注释(特别是当编译器执行magic 隐式声明特殊成员时幻灯片部分...)。

这是我最终的结果(没有显式复制和交换):

#include <iostream>

class Bar {
public:
  Bar(unsigned int bottles=0) : bottles(bottles) { enforce(); } // The only point of enforcement

  friend std::ostream & operator<<(std::ostream & out, Bar const & b) {
    out << b.bottles << " bottles";
    return out;
  }

private:
  unsigned int bottles;
  void enforce() { bottles /= 2; bottles *=2; }
};

int main () {
  Bar man (5);
  Bar woman;

  std::cout << "Before -> m: " << man << " / w: " << woman << std::endl;
  using std::swap; // Argument dependent lookup
  swap(man, woman);
  std::cout << "After  -> m: " << man << " / w: " << woman << std::endl;

  return 0;
}

现在,如果Bar继承自Foo(不需要enforce)会发生什么。这是最初的用例,让我觉得我需要展开自己的特殊功能,并从副本的复制部分和交换习语中获益enforce约束。事实证明,即使在这种情况下,我也不需要:

#include <iostream>

class Foo {
public:
  Foo(unsigned int bottles=11) : bottles(bottles) {} // This is odd on purpose

  virtual void display(std::ostream & out) const {
    out << bottles << " bottles";
  }

protected:
  unsigned int bottles;
};

std::ostream & operator<<(std::ostream & out, Foo const & f) {
  f.display(out);
  return out;
}

class Bar : public Foo {
public:
  Bar(unsigned int bottles=0) : Foo(bottles) { enforce(); }
  Bar(Foo const & f) : Foo(f) { enforce(); }

  void display(std::ostream & out) const override {
    out << bottles << " manageable bottles";
  }

private:
  void enforce() { bottles /= 2; bottles *=2; }
};

int main () {
  Bar man (5); // Again odd on purpose
  Bar woman;

  std::cout << "Before -> m: " << man << " / w: " << woman << std::endl;
  using std::swap; // Argument dependent lookup
  swap(man, woman);
  std::cout << "After  -> m: " << man << " / w: " << woman << std::endl;

  Foo fool(7); // Again odd
  Bar like(fool);
  std::cout << fool << " -> (copy) " << like << std::endl;
  Bar crazy;
  crazy = fool;
  std::cout << fool << " ->   (=)  " << crazy << std::endl;

  return 0;
}