在单独的线程中使用参数启动成员函数 [英] Starting a member function with arguments in a separate thread

查看:118
本文介绍了在单独的线程中使用参数启动成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我试图从这样的线程中调用该函数:

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

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;

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

但是,这将导致以下错误:lvalue required as unary ‘&’ operand

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?

推荐答案

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

Just add the arguments to the thread's constructor:

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

当函数接受引用时,应使用std::ref()这样:

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

这篇关于在单独的线程中使用参数启动成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆