Consider a program with three threads A,B,C.
They have a shared global object G.
I want to use an atomic variable(i) inside G which is written by Thread B and Read by A.
My approach was:
declare i in G as:
G* pG; //this is available inside A and B
pG->i = 23;
int k = pG->i;
Like JV says, it depends what your definition of "correct" is. See http://preshing.com/20120612/an-introduction-to-lock-free-programming/. If it doesn't need to synchronize with anything, you should use
std::memory_order_relaxed stores instead of the default sequential consistency stores, so it compiles to more efficient asm (no memory barrier instructions).
But yes, accessing an atomic struct member through a pointer is fine, as long as the pointer itself is initialized before the threads start.
If the struct is a global, then don't use a pointer to it, just access the global directly. Having a separate variable that always points to the same global is an extra level of indirection for no benefit.
If you want to change the pointer, it also needs to be
std::atomic<struct foo *> pG, and changing it gets complicated as far as deciding when it's safe to free the old data after changing it.