根据移动赋值运算符移动构造函数
Move constructor in terms of move assignment operator
在我们项目的代码库中,我发现了这样的东西:
struct MeshData {
MeshData() {}
MeshData(MeshData&& obj) { *this = std::move(obj); }
MeshData& operator=(MeshData&& obj) {
if (this != &obj) {
indexes = std::move(obj.indexes);
}
return *this;
}
std::vector<int> indexes;
};
根据移动赋值实现移动构造对我来说似乎是一个减少代码重复的好主意,但在查找信息后我没有找到任何关于此的具体建议。
我的问题是:这是反模式还是在任何情况下都不应该这样做?
如果您的类型具有没有默认构造函数的数据成员,则不能这样做,如果它们具有昂贵的默认构造函数,则不应这样做:
struct NoDefaultCtor {
NoDefaultCtor() = delete;
NoDefaultCtor(int){}
};
struct Foo {
Foo(Foo&& obj) { *this = std::move(obj); }
Foo& operator=(Foo&& obj) {
if (this != &obj) {
thing = std::move(obj.thing);
}
return *this;
}
NoDefaultCtor thing;
};
出现此错误:
<source>: In constructor 'Foo::Foo(Foo&&)':
<source>:10:20: error: use of deleted function 'NoDefaultCtor::NoDefaultCtor()'
Foo(Foo&& obj) { *this = std::move(obj); }
^
<source>:5:5: note: declared here
NoDefaultCtor() = delete;
这是因为所有数据成员必须在进入构造函数体之前构造。
但是,最好的建议是遵循 Rule of Zero 并完全避免编写那些特殊成员。
当成员变量的移动构造函数和移动运算符可能产生不同的结果时,这种方法的一个缺陷就会显现出来。例如,如果 indexes
是一个 vector
,使用自定义分配器 std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value
评估为 true
,就会发生这种情况。在这种情况下,专用移动构造函数将同时移动分配器和数据而不会抛出异常,而调用移动赋值将导致分配新存储并且所有项目移动构造导致相当大的开销并阻止移动构造函数不抛出。
在我们项目的代码库中,我发现了这样的东西:
struct MeshData {
MeshData() {}
MeshData(MeshData&& obj) { *this = std::move(obj); }
MeshData& operator=(MeshData&& obj) {
if (this != &obj) {
indexes = std::move(obj.indexes);
}
return *this;
}
std::vector<int> indexes;
};
根据移动赋值实现移动构造对我来说似乎是一个减少代码重复的好主意,但在查找信息后我没有找到任何关于此的具体建议。
我的问题是:这是反模式还是在任何情况下都不应该这样做?
如果您的类型具有没有默认构造函数的数据成员,则不能这样做,如果它们具有昂贵的默认构造函数,则不应这样做:
struct NoDefaultCtor {
NoDefaultCtor() = delete;
NoDefaultCtor(int){}
};
struct Foo {
Foo(Foo&& obj) { *this = std::move(obj); }
Foo& operator=(Foo&& obj) {
if (this != &obj) {
thing = std::move(obj.thing);
}
return *this;
}
NoDefaultCtor thing;
};
出现此错误:
<source>: In constructor 'Foo::Foo(Foo&&)':
<source>:10:20: error: use of deleted function 'NoDefaultCtor::NoDefaultCtor()'
Foo(Foo&& obj) { *this = std::move(obj); }
^
<source>:5:5: note: declared here
NoDefaultCtor() = delete;
这是因为所有数据成员必须在进入构造函数体之前构造。
但是,最好的建议是遵循 Rule of Zero 并完全避免编写那些特殊成员。
当成员变量的移动构造函数和移动运算符可能产生不同的结果时,这种方法的一个缺陷就会显现出来。例如,如果 indexes
是一个 vector
,使用自定义分配器 std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value
评估为 true
,就会发生这种情况。在这种情况下,专用移动构造函数将同时移动分配器和数据而不会抛出异常,而调用移动赋值将导致分配新存储并且所有项目移动构造导致相当大的开销并阻止移动构造函数不抛出。