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

标签 c++ multithreading qt stdthread

我有一个成员函数 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);

由于您的函数接受一个引用,您应该像这样使用std::ref():

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

// ...

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

关于c++ - 在单独的线程中启动带参数的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43237503/

相关文章:

Qt 4.5 - QList::QList(const QList&) - 这是一个深拷贝构造函数吗?

qt - ROS Qt 媒体在重新制作之前不显示

c++ - 为什么图像没有合并

c++ - boost 、互斥概念

multithreading - 划分工作,将任务分配给线程数组

ios - 如何理解苹果文档中CoreData的父/子模型?

python - PyQT实时显示串口数据在QtCore.QTimer.singleShot()上抛出最大递归深度超出异常

c++ - 在 Linux 上使用 MinGW 交叉编译 C++ 代码,目标是 Windows : error happens

c++ - 我可以检测成员函数是否存在并且可以被 C++ 中的 friend 访问吗?

C++——typedef "inside"模板参数?