I was going through some problems with my atomic container and saw this link.
Is there a reason why std::atomic isn't copy-constructable? The solution seems to be this where they just pass the T value to the non-atomic constructor with the atomic load function (if I'm not mistaken).
So in general, is this copy constructor thread safe?
template<typename T>
struct MobileAtomic
{
std::atomic<T> atomic;
explicit MobileAtomic(std::atomic<T> const& a) : atomic(a.load()) {}
};
Is there a reason why std::atomic isn't copy-constructable?
Yes.
When you are asking for a copy constructible atomic, you're asking for the "normal" rules of single-threaded sequential consistency to apply to a variable that doesn't follow those rules.
In essence, there is no generalized solution.
By using the constructor you show in the question, you sacrifice a deterministic outcome in that you have no guarantee that the source and destination objects are equivalent after construction is complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With