I use the following code:
struct WorkData
{
std::string name;
std::function<void(std::string)> Callback;
WorkData(){};
WorkData(const WorkData& other)
{
name = other.name;
Callback = std::ref(other.Callback);
}
};
WorkData data; // this is the data to pass to queue_task() function bellow
data.Callback = std::bind(&ResultProcessor::Handler, resProc, std::placeholders::_1);
template <typename Functor>
void queue_task(Functor& fn, WorkData& workData )
{
group.run([&fn, workData](){
workData.Callback("resultComming"); // runtime ERROR- access violation
});
}
queue_task function queues work to be done asynchronously on another thread (by calling group.run(lambda) from above). The problem that I’m experiencing is that I get an access violation when trying to call workData.Callback().
The reason I make a copy of workData inside group.run() is because I want to capture workData by value so that when the group.run() lambda executes it has a copy of the state when queue_task() was called. I would expect that workData.Callback() would execute on the instance of object passed on line:
data.Callback = std::bind(&ResultProcessor::Handler, resProc, std::placeholders::_1);
EDIT: resProc from above is alive (not destroyed) when the crash line is called
The use of
std::refin your copy constructor means that you keep a reference to the oldWorkData‘sCallbackmember, not a copy. You wantCallback = other.Callbackto make a copy to avoid an access violation (probably from accessing the old callback after it has been freed). In order to keep a reference toresProcin thestd::function, you need to usestd::ref(resProc)in the call tostd::bind.