2

I need to refactor some C++ code that needs some accesses to become atomic.

std::atomic is nice, but can be assigned from and converted to value_type, which means that existing call sites are taken over without complaint.

Is there a variant of std::atomic that requires me to explicitly call load()/store()/compare_exchange_weak everywhere?

Simon Richter
  • 28,572
  • 1
  • 42
  • 64
  • 9
    I am not aware of such variant. But you can write it yourself as a wrapper for `std::atomic`, exposing only the methods you want. – wohlstad May 17 '23 at 08:46
  • Why do you want to explicitly call load()/store()/compare_exchange_weak everywhere? – Caleth May 17 '23 at 09:08
  • 2
    I would just manually re-name the field from, say `m_value` to `m_atomicValue`. Then you have to go around and change the name everywhere manually anyway, so you can examine where it is passed to external functions. – Aykhan Hagverdili May 17 '23 at 09:09
  • 2
    @Caleth: Seems reasonable to me as a coding-style choice, to highlight the shared-variable accesses and make it easier to spot them in code that also uses some local vars. If you want to enforce that, not providing operator= and cast overloads seems a good way. Also, if you intend to only use `acquire` / `release` operations, the default `seq_cst` is slower so you want to catch anywhere you forgot and used it implicitly. (For that you'd also want to delete the operator++ and operator-- overloads. Making the memory-order arg not defaulted would be useful but maybe not worth the effort.) – Peter Cordes May 17 '23 at 09:32
  • fwiw, `std::atomic< wrapper>` would let you choose between explicit from/to `T` and implicit from/to `wrapper` – 463035818_is_not_an_ai May 17 '23 at 10:06

0 Answers0