在我们项目的代码库中,我发现了这样的东西:
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;
};
在 move 分配方面实现 move 构造对我来说似乎是一个减少代码重复的聪明主意,但在查找信息后我没有找到任何关于此的具体建议。
我的问题是:这是一个反模式还是在某些情况下不应该这样做?
最佳答案
如果您的类型具有没有默认构造函数的数据成员,则不能这样做,如果它们具有昂贵的默认构造函数,则不应这样做:
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并完全避免编写那些特殊成员。
关于c++ - 根据 move 赋值运算符 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48950096/