那么,如今基础类如何在C++ 11中编写?

Vik*_*ehr 3 c++ class-design rvalue move-semantics c++11

更新:我使用MSVC10,它没有给我默认的移动语义

假设我想创建一个带有几个非pod成员的常规类;

class Foo {
NonPodTypeA a_;
NonPodTypeB b_;
}
Run Code Online (Sandbox Code Playgroud)

像往常一样,我实现了一个复制构造函数,以及一个使用copy-constructor的赋值运算符:

Foo(const Foo& other) : a_(other.a_), b_(other.b_) {}
Foo& operator=(const Foo& other) { 
  Foo constructed(other);
  *this = std::move(constructed);
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

然后我实现了move-constructor和move-assignment,它使用std :: swap代替std :: move为所有成员,因为它们可能在move-semantics可用之前编写,因为move-semantics已实现,我可以省略实现交换成员函数:

Foo(Foo&& other) {
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
}
Foo& operator=(Foo&& other) { 
  ::std::swap(a_, other._a);
  ::std::swap(b_, other._b);
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

这就是我的问题; 假设我对会员一无所知,可以在这里做些更通用的事吗?

例如,move-constructor与const声明的成员不兼容,但如果我实现移动构造函数,因为Foo(Foo&& other) : a_(std::move(other.a_)), b_(std::move(other.b_)){}我不能确保没有复制移动语义的类?我可以以一种聪明的方式在移动分配中使用移动构造函数吗?

R. *_*des 6

呃,什么都不做.所有这些都是自动生成的1.您需要手动编写它们的唯一时间是当类处理资源时(然后您需要遵循规则三).这也是以前的样子.现在唯一的区别是,以后,你认为三的规则,你可能要实施搬迁成员无论是语义(即之举,只是对象)或性能方面的原因(移动通常比拷贝更快的).


1. MSVC 10不会自动生成移动构造函数.在这种情况下,您可能想要自己写移动成员:(