c++ - 根据 move 赋值运算符 move 构造函数

标签 c++ c++11 move

在我们项目的代码库中,我发现了这样的东西:

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/

相关文章:

android - 通过拖动在相机中 move 时,它总是每秒 move 到当前位置

c++ - 数组下标的无效类型 ‘<unresolved overloaded function type>[int]’ - C++

c++ - 如何从 snprintf() 获得 -1

c++ - 模运算——竞技编程

c++ - 对基类和派生类使用静态容器

c++ - 删除和默认函数真实世界的例子

滚动时Android RecyclerView重复项

c++ - make 在 swig create ruby​​ wrapper 上失败

c++ - 枚举(类)允许的类型是什么?

Android 图像拖动并从一种布局 move 到另一种布局