17

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Juster
  • 732
  • 1
  • 10
  • 26

1 Answers1

20

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 11
    Worth noting that `memory_order_seq_cst` is the strongest memory ordering. There's no reason to specify a different one, other than to improve performance in situations where you don't need full sequential consistency. – Sneftel Sep 09 '14 at 09:11
  • 4
    I prefer `load` / `store` because it indicates the variable is an atomic one, it enhances code readability! – Victor Lamoine Dec 26 '16 at 10:56