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_)){}我不能确保没有复制移动语义的类?我可以以一种聪明的方式在移动分配中使用移动构造函数吗?
| 归档时间: |
|
| 查看次数: |
304 次 |
| 最近记录: |