在赋值移动运算符内部使用交换

Using swap inside assignment move operator

本文关键字:交换 内部 运算符 赋值 移动      更新时间:2023-10-16

I c++编程语言13.6.2 std::swap用于实现移动语义,其思想如下:

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

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

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

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

您需要在某个时刻对每个成员调用move。这可以通过调用swap(*this, other);并实现swap的专门化来实现,也可以通过在每个成员上直接调用swap来实现,或者通过让std::swap调用移动分配运算符来实现。

不应使用swap执行移动分配。

我们已经有了一个优秀的指南";复制和交换";成语,这里:什么是复制和交换成语?

另请阅读C++11中的复制和交换习语应该变成复制和移动习语吗?

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

class greenCars
{
 public:
  greenCars(){std::cout<<"DSn";}
  // defaulted move operations (member-wise moves)
  greenCars(greenCars&& other) = default;
  greenCars& operator=(greenCars&& other) = default;
  // copy construction is defaulted (member-wise copies)
  greenCars(const greenCars& other) = default;
  // copy assignment uses copy-and-move for exception safety
  greenCars& operator=(greenCars other)
  {
    return *this = std::move(other);
  }
};