Can I call a function of base type class when calling store() of atomic? C++

Viewed 71

In my code, I have an atomic array of objects I have created from a self defined class. In short, the class looks like this:

class myObj{
public:
    //some members here...

    //constructor
    myObj()noexcept{
        //some code here
    }

    //function I want to call
    void myFunc(){//some code here}
};

Now let's say I have a single atomic object, instead of an array. I would declare it in main.cpp like below:

std::atomic<myObj> atomic_var;

I of course want to (atomically) store something in the variable above. Thus, I first create a temporary myObj, then I call .store() on my atomic variable.

myObj temp;
atomic_var.store(temp, std::memory_order_...);

where memory order does not matter right now.

Is it possible to call myObj::myFunc() when .store() is called as above?

Thank you.

1 Answers

Is it possible to call myObj::myFunc() when .store() is called as above?

std::atomic<myObj>::is_lock_free is false because myObj is a user-defined type. That means that std::atomic<myObj> is implemented using a mutex, but that mutex isn't exposed.

What you can do is make that mutex a data member of myObj and implement myObj& operator=(myObj const&) to lock that mutex, do its job (e.g. also call myObj::myFunc()) and then unlock the mutex. And use myObj instead of std::atomic<myObj>.

An alternative is to implement a custom full specialization of std::atomic<myObj>, but that may be more work than it is worth.

Related