13

I see that this is potentially answered in question Must I call atomic load/store explicitly?.

So for sake of clarity I will restate my question succinctly in the hopes that future readers find this clear.

Is

std::atomic<bool> b(false);
bool x = b;

Same as

std::atomic<bool> b(false);
bool x = b.load();

And

std::atomic<bool> b(false);
b = true;

Same as

std::atomic<bool> b(false);
b.store(true);

If this is indeed the case then:

  1. why have 2 options? what is the apparent benefit?
  2. Is it good practice when dealing with atomics to prefer the more verbose load()/store() over the potentially confusing assignment(=) which could mean either depending on whether LHS or RHS is the atomic.

NOTE I am already aware of the fact that both variables cannot be std::atomic i.e LHS and RHS as it is not possible to read and write atomically in one instruction.

Community
  • 1
  • 1
BGR
  • 529
  • 4
  • 10

1 Answers1

11

Yes, they are the same. I think the reason the overloaded operators are provided is for convenience. Not to mention making it easier to convert existing code to use atomics.

Personally, I prefer to be explicit with load and store always. I think it's better practice and forces you to remember that you're dealing with an atomic.

Also, those functions allow you to specify other memory orders, which is not possible with the overloaded operator versions.

paddy
  • 52,396
  • 6
  • 51
  • 93
  • Aha! so when we use = is it by std::default memory_order_seq_cst? – BGR Jan 21 '16 at 05:27
  • 1
    Yes. According to [cppreference](http://en.cppreference.com/w/cpp/atomic/atomic/operator%3D), `operator =` _"Atomically assigns a value t to the atomic variable. Equivalent to `store(desired)`."_, and similar for `operator T`. – paddy Jan 21 '16 at 05:29
  • 3
    Also, using load() forces a copy to another variable. Using assignment makes code often reload from the atomic over and over when it doesn't need to. – Zan Lynx Jan 21 '16 at 06:00
  • 2
    Zan Lynx What do you mean by reload from atomic over and over again? I don't understand – BGR Jan 21 '16 at 12:11
  • 1
    An additional question regarding this: why `std::acomic a = true; std::atomic b = a;` is not allowed, but `std::acomic a = true; std::atomic b = a.load();` is? – GregPhil Aug 29 '17 at 09:02