简体   繁体   中英

C++ Making a thread and passing Object by reference

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

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

You can simply use Orders customerOrders;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM