Anubhav Srivastava
Anubhav Srivastava

Reputation: 229

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

Upvotes: 2

Views: 399

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63912

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

Upvotes: 3

NathanOliver
NathanOliver

Reputation: 180955

One shorter way I could see to do this would be to move MANY MORE FIELDS HERE into a different class and make that a base class of Test, Then you just have one line of code to call the move assignment operator of the base class. That would look like

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

Upvotes: 3

Related Questions