简体   繁体   English

C ++创建线程并按引用传递对象

[英]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 c:\\程序文件(x86)\\ Microsoft Visual Studio \\ 2017 \\ community \\ vc \\ tools \\ msvc \\ 14.11.25503 \\ include \\ thr \\ xthread(240):错误C2672:'std :: invoke':没有匹配的重载函数找到1> c:\\ program files(x86)\\ microsoft visual studio \\ 2017 \\ community \\ vc \\ tools \\ msvc \\ 14.11.25503 \\ include \\ thr \\ xthread(248):注意:请参见对函数模板实例化的引用'void std :: _ LaunchPad <_Target> :: _ Execute <0,1>(std :: tuple>&,std :: integer_sequence <_Ty,0,1>)'正在编译

Orders customerOrders(); declares a function. 声明一个函数。 This is known as the most-vexing parse. 这被称为最烦人的解析。

You can simply use Orders customerOrders; 您可以简单地使用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 ). (并且正如FrançoisMoisan讲的那样,在声明customerOrders时您有一个错字)。

without any std::cref . 没有任何std::cref However, your thread is later detached, but the customerOrders is destroyed by the return of main . 但是,您的线程稍后会被分离,但是main的返回会破坏customerOrders That is probably an undefined behavior since OrderServer then works with a reference to some object which does not exist anymore. 这可能是未定义的行为,因为OrderServer随后使用对不再存在的某个对象的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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