Search code examples
c++c++11stdatomic

What is the difference between explicit atomic load/store and usual operator= and operator T?


Consider these two variants:

std::atomic<int> a;
a = 1;
int b = a;

and

std::atomic<int> a;
a.store(1);
int b = a.load();

I see from the documentation that the second one is fully atomic, but I don't understand when I should use which and what's the difference in detail.


Solution

  • Those two examples are equivalent; operator= and operator T are defined to be equivalent to calling store and load respectively, with the default value for the memory_order argument.

    If you're happy with that default value, memory_order_seq_cst, so that each access acts as a memory fence, then use whichever looks nicer to you. If you want to specify a different value, then you'll need to use the functions, since the operators can't accept a second argument.