I have a class with an atomic member and i want to write a copy constructor:
struct Foo
{
std::atomic<int> mInt;
Foo() {}
Foo(const Foo& pOther)
{
std::atomic_store(mInt, std::atomic_load(pOther.mInt, memory_order_relaxed), memory_order_relaxed);
}
};
But i don't know which ordering i must use, because i don't know where and when this copy constructor will be called.
Can i use relaxed
ordering for copy constructor and assignment operator?
No, if you don't know how it will be used, you should use memory_order_seq_cst
to be safe. If you use memory_order_relaxed
, you could run into issues with instructions being reordered.
You only need a stronger memory ordering than memory_order_relaxed
, if your copy operation is supposed to synchronize with other operations on a different thread.
However, this is almost never the case, as a thread safe copy constructor will almost always require some external synchronization or an extra mutex anyway.
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