Search code examples
c++11atomic

C++ atomic for pointers to user defined objects


Can I have pointers to user defined functions as the template type for atomic variables ? Something like this

class A
{
int d;
public:
 void foo() { cout<<"Hellow wolrd!"; }
};

int main()
{
atomic<A*> ptrA;
//now how to call A::foo() from ptrA ?

}

Solution

  • You have two ways to call the method:

    Method 1:

    (*ptrA).foo();
    

    Method 2

    A* a = ptrA.load();
    
    a->foo();
    

    I don't know anything about your multi-threaded scenario to advise how best to avoid any pitfalls as you've not provided much information but the second way obviously allows you to guard against certain outcomes. Note also that the load method on std::atomic can accept a number of different memory ordering constraints.