class 具有原子成员时更短的移动构造函数

Shorter move constructor when class has an atomic member

我正在尝试为包含原子变量的 class 编写移动赋值运算符。由于按照 this answer,原子不可移动,我意识到我必须编写一个移动赋值运算符来加载原子然后存储它。但是,我必须在 class 中的所有其他字段上手动调用 move。有没有更短的方法来做到这一点(假设所有其他字段都是可移动的)?

class Test {
    std::atomic<int*> val{nullptr};
    // MANY MORE FIELDS HERE

    Test& operator=(Test&& other) {
        this->val = other.val;
        // init the many other fields here
        return *this;
    }
};

考虑

class Test {
    std::atomic<int*> val{nullptr};
    struct Movables
    {
        // MANY MORE FIELDS HERE
    } movables;

public:
    Test& operator=(Test&& other) {
        this->val.exchange(other.val);
        this->movables = std::move(other.movables);
        return *this;
    }
};

我能想到的一个更短的方法是将 MANY MORE FIELDS HERE 移动到另一个 class 并使它成为 Test 的基础 class,然后你只需一行代码就可以调用基class的移动赋值运算符。那看起来像

class Base {
public:
    // MANY MORE FIELDS HERE
};

class Test : private Base {
    std::atomic<int*> val{nullptr};
    
public:
    Test& operator=(Test&& other) {
        this->val = other.val;
        Base::operator=(std::move(other));
        return *this;
    }
};