更新:我使用 MSVC10,它没有给我默认的移动语义
假设我想创建一个包含几个非 pod 成员的常规类;
class Foo {
NonPodTypeA a_;
NonPodTypeB b_;
}
像往常一样,我实现了一个复制构造函数和一个使用复制构造函数的赋值运算符:
Foo(const Foo& other) : a_(other.a_), b_(other.b_) {}
Foo& operator=(const Foo& other) {
Foo constructed(other);
*this = std::move(constructed);
return *this;
}
然后我实现 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;
}
这是我的问题;假设我对成员一无所知,这里可以做一些更笼统的事情吗?
例如,移动构造函数与 const 声明的成员不兼容,但是如果我实现移动构造函数,因为Foo(Foo&& other) : a_(std::move(other.a_)), b_(std::move(other.b_)){}
我不能确定没有移动语义的类不会被复制?我可以以某种巧妙的方式在移动分配中使用移动构造函数吗?