【发布时间】:2012-03-11 22:17:11
【问题描述】:
更新:我使用 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;
}
这是我的问题; 假设我对成员一无所知,这里可以做一些更笼统的事情吗?
例如,move-constructor 与 const 声明的成员不兼容,但如果我将 move 构造函数实现为Foo(Foo&& other) : a_(std::move(other.a_)), b_(std::move(other.b_)){},我不能确定没有 move-semantics 的类不会被复制?
我可以以某种巧妙的方式在 move-assignment 中使用 move-constructor 吗?
【问题讨论】:
-
像往常一样,你什么也不做。让 a_ 和 b_ 照顾好自己。
-
错误多于正确。除此之外,不要完全限定
std::swap。 -
ADL 应该用于调用
swap,而不是显式限定(除非该限定是boost::swap,它将在内部使用ADL)。 -
ildjarn:我还是不明白,如果类中实现了 move-semantics,std::swap 会使用它(至少在 MSVC10 中)
-
@ViktorSehr:您不能向
namespace std添加重载。这就是您要从 ADL 命名空间中选择swap的原因。
标签: c++ c++11 class-design move-semantics rvalue