在单独的线程中启动带参数的成员函数

Starting a member function with arguments in a separate thread

我有一个成员函数MyClass::doStuff(QString & str)

我正在尝试从这样的线程调用该函数:

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

但是,这会导致错误:

/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;

所以我试图给它一个论点:

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

但是,这会导致此错误:lvalue required as unary ‘&’ operand

我如何从单独的线程中处理 运行 带有参数的成员函数?

只需将参数添加到线程的构造函数中:

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

由于您的函数接受 reference,因此您应该像这样使用 std::ref()

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

// ...

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