使用swap内部赋值移动运算符

时间:2015-11-28 18:33:15

标签: c++ c++11

我用c ++编程语言13.6.2 std :: swap用于实现移动语义的想法如下:

class deutscheSchweine{
 public:
  deutscheSchweine(){std::cout<<"DS\n";}
  deutscheSchweine& operator=(const deutscheSchweine& other){
   deutscheSchweine tmp;
   swap(*this, tmp);
   return *this;
  }
  deutscheSchweine(deutscheSchweine&& other){}
  deutscheSchweine& operator=(deutscheSchweine&& other){
   swap(*this, other);
   return *this;
  }
};


int main(){
deutscheSchweine ds;
deutscheSchweine ds2;
ds2 = ds;

上面的示例在调用赋值之后我们可以使用移动语义从临时中复制avid,但是此示例导致递归调用移动赋值。我的问题是我们可以在移动语义中使用swap但是以某种正确的方式吗?

1 个答案:

答案 0 :(得分:0)

通过交换实现拷贝分配是一个好主意,但你错过了一些细节。

您需要在某个时刻调用每个成员的移动。这可以通过致电swap(*this, other);并实施swap专业化,直接致电每个成员swap,或让std::swap调用您的移动分配运算符来完成

不应使用swap实现移动分配。

我们已经有了一个很好的“复制和交换”习语指南,在这里:What is the copy-and-swap idiom?

另请阅读Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11?

最后,您想要的(假设您的成员对象设计正确)是:

class deutscheSchweine
{
 public:
  deutscheSchweine(){std::cout<<"DS\n";}

  // defaulted move operations (member-wise moves)
  deutscheSchweine(deutscheSchweine&& other) = default;
  deutscheSchweine& operator=(deutscheSchweine&& other) = default;

  // copy construction is defaulted (member-wise copies)
  deutscheSchweine(const deutscheSchweine& other) = default;

  // copy assignment uses copy-and-move for exception safety
  deutscheSchweine& operator=(deutscheSchweine other)
  {
    return *this = std::move(other);
  }
};