首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用交换内部赋值移动操作符

使用交换内部赋值移动操作符
EN

Stack Overflow用户
提问于 2015-11-29 02:33:15
回答 1查看 1K关注 0票数 0

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

代码语言:javascript
运行
复制
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;

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

EN

回答 1

Stack Overflow用户

发布于 2015-11-29 02:42:26

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

您需要在某个时刻对每个单独的成员调用move。这可以通过调用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?

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

代码语言:javascript
运行
复制
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);
  }
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33974934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档