如何在运行成员函数的类中声明线程?根据网上搜索,我尝试了几种方法:这个
std::thread t(&(this->deQRequest));
这个
std::thread t([this]{ deQRequest(); });
这个
std::thread t(&this::deQRequest, this);
或
std::thread t(&this::deQRequest, *this);
它们都不起作用。
然后我尝试了以下代码,它有效:
std::thread spawn() {
return std::move(
std::thread([this] { this->deQRequest(); })
);
}
但我的问题是,为什么这个
std::thread t([this]{ deQRequest(); });
不起作用?它总是提醒一个错误:"Explicit类型丢失,假定为'int'"one_answers"应为声明"。
我的deQRequest函数是同一类中的一个成员函数,我的类如下所示:
class sender{
public:
void deQRequest(){
//some execution code
};
private:
// here I try to declare a thread like this:std::thread t([this]{ deQRequest(); });
}
但我的问题是,为什么这个
std::thread t([this]{ deQRequest(); });
不起作用?它总是提醒一个错误:"缺少显式类型,假定为"int",并且"应为声明"。
它不是有效的lambda函数语法。this
是deQRequest
的隐式参数,不能通过这种方式传递。
与std::thread
的构造函数引用一样,它接受一个函数参数,以及应该传递到那里的参数:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
你的班级
class sender{
public:
void deQRequest(){
//some execution code
};
private:
void foo() { // I just assume you're using some private function
// here I try to declare a thread like
// this:std::thread t([this]{ deQRequest(); });
}
std::thread theThread; // I also assume you want to have a `std::thread`
// class member.
}; // <<< Note the semicolon BTW
声明了一个成员函数,并且您需要将该成员函数std::bind()
添加到(您当前的)类实例:
void foo() {
theThread = std::thread(std::bind(&sender::deQRequest,this));
}