1

I have a some simple class:

class List {
    List *next;
    int value;
};

And a std::atomic<List *> Ltag. How can I extract the actual List * from Ltag? I tried Ltag->value = 80 which didn't work. Casting didn't work as well.

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 4
    `Ltag.load()->value = 80;` – Raymond Chen Jul 15 '20 at 04:28
  • 2
    So you have an atomic pointer to non-atomic data. You don't need to *extract* it, just load it. `atomic` doesn't overload `operator->` presumably so you don't forget that the store won't be an atomic operation. – Peter Cordes Jul 15 '20 at 04:28
  • 1
    Does [this Q/A](https://stackoverflow.com/questions/27069103/misunderstanding-of-atomic-structs-and-pointers) help you? Also, an important thing to remember is that with something like `std::atomic`, only the pointer address is safe from race conditions, not the pointed-to object. If multiple threads read/write to/from the pointed-to object, you'll have UB. – alter_igel Jul 15 '20 at 04:30
  • 1
    Side note: Don't get overconfident with `atomic`. More often that not you want to protect an entire transaction, not just one part of it. – user4581301 Jul 15 '20 at 04:30
  • @alterigel: [Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load](https://stackoverflow.com/q/30121194) is closer to a duplicate, it's about using `.load()->member` on `atomic`, rather than about `atomic` – Peter Cordes Jul 15 '20 at 04:34

1 Answers1

3

You can take advantage of the conversion operator of std::atomic.

(*Ltag).value = 80;

Or use load() to get the value explicitly.

Ltag.load()->value = 80;

PS: You're using std::atomic with pointer, that means there might be data race on the pointed object.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 3
    It's worth noting that if multiple threads are doing this, you'll still have a race condition, since only the _address_ is atomic, not the object that is pointed to. – alter_igel Jul 15 '20 at 04:32
  • re: safety: [Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load](https://stackoverflow.com/q/30121194) – Peter Cordes Jul 15 '20 at 04:36