Search code examples
c++atomicmove-semanticsstdatomic

Shorter move constructor when class has an atomic member


I am trying to write a move assignment operator for a class that contains an atomic variable. Since atomic's are not movable as per this answer, I've realized that I have to write a move assignment operator that loads the atomic and then stores it. But, I then have to manually call move on all the other fields in my class. Is there a shorter way to do this (assuming all the other fields are movable)?

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;
    }
};

Solution

  • Consider

    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;
        }
    };