【问题标题】:Using swap inside assignment move operator在赋值移动运算符中使用交换
【发布时间】:2016-03-02 16:36:11
【问题描述】:

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

我上面的例子在调用赋值之后我们可以使用移动语义来从临时复制,但是这个例子导致递归调用移动赋值。我的问题是我们可以在移动语义中以某种适当的方式使用交换吗?

【问题讨论】:

  • 如果你想以swap的形式实现move assignment,它需要是你自己的swap,而不是默认的swap,它是根据move assignment(和move构造)来实现的,并且会导致在海龟中一直向下......
  • 谢谢这是对我问题的正确答案,因为在书中将交换与移动分配一起使用时可能没有提到这个细节。
  • deutscheSchweine 是攻击性的还是农业用语?

标签: c++ c++11


【解决方案1】:

通过交换实现复制分配是个好主意,但您错过了一些细节。

您需要在某个时候对每个单独的成员调用 move。这可以通过调用swap(*this, other); 并实现swap 的特化,通过直接对每个成员调用swap,或让std::swap 调用您的移动赋值运算符来完成。

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

我们已经有了“copy-and-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);
  }
};

【讨论】:

  • 嗯,这在重载决议中会很模糊。 TT&amp;&amp; 没有决胜局。
  • deutscheSchweine(deutscheSchweine other) = default; 不是有效的构造函数签名
猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 2016-05-19
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多