0
votes

Currently trying to pass an object by reference to another thread but I get errors when I try to build my solution.

void OrderServer(Orders& customerOrders)
{
    Item tempItem;
    customerOrders.add(tempItem);
}

int main()
{
Orders customerOrders();
auto serverThread = std::thread(OrderServer, std::cref(customerOrders));
serverThread.detach();
return 0;
}

The following is the error:

c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.11.25503\include\thr\xthread(240): error C2672: 'std::invoke': no matching overloaded function found 1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.11.25503\include\thr\xthread(248): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0,1>(std::tuple> &,std::integer_sequence<_Ty,0,1>)' being compiled

2
You are passing a std::cref to a non-constant parameter function. Try passing std::ref() or making your function accept a const parameter reference. - Galik
Your thread function accepts by a non-const reference. But you create a const reference wrapper with std::cref. - StoryTeller - Unslander Monica

2 Answers

2
votes

Orders customerOrders(); declares a function. This is known as the most-vexing parse.

You can simply use Orders customerOrders;

0
votes

You could try simply:

auto serverThread = std::thread(OrderServer, customerOrders);

(and as told by François Moisan you have a typo when declaring customerOrders).

without any std::cref. However, your thread is later detached, but the customerOrders is destroyed by the return of main. That is probably an undefined behavior since OrderServer then works with a reference to some object which does not exist anymore.