Starting a member function with arguments in a separate thread

巧了我就是萌 提交于 2019-12-08 04:45:03

问题


I have a member function MyClass::doStuff(QString & str)

I am trying to call that function from a thread like this:

std::thread thr(&MyClass::doStuff, this);

However, that results in an error:

/usr/include/c++/4.8.2/functional:1697: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (MyClass::*)(QString&)>(MyClass*)>’ typedef typename result_of<_Callable(_Args...)>::type result_type;

So I've attempted to give it the argument:

QString a("test");
std::thread thr(&MyClass::doStuff(a), this);

However, that results in this error: lvalue required as unary ‘&’ operand

How would I go about running that member function with an argument, from a separate thread?


回答1:


Just add the arguments to the thread's constructor:

QString a("test");
std::thread thr(&MyClass::doStuff, this, a);

As your function accepts a reference you should use std::ref() like this:

MyClass::doStuff(QString& str) { /* ... */ }

// ...

QString a("test");
std::thread thr(&MyClass::doStuff, this, std::ref(a)); // wrap references


来源:https://stackoverflow.com/questions/43237503/starting-a-member-function-with-arguments-in-a-separate-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!