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;
}
};
seq_cst
, which costs extra on many non-x86 platforms vs. weaker loads. If you're moving from the old object, presumably it's no longer valid so it would be UB for any other threads to still possibly be accessing its atomic member. So you might wantother.val.load(std::memory_order_relaxed)
, or possibly acquire, although anything like.join
or a syncs-with should transitively guarantee visibility of stuff older than the member values. (Avoiding seq_cst on the store helps much more on most CPUs.)