gpt4 book ai didi

C++ 11 : Start thread with member function and this as parameter

转载 作者:太空狗 更新时间:2023-10-29 19:39:29 27 4
gpt4 key购买 nike

使用这段代码,我得到了错误:

错误 1 ​​error C2064: term does not evaluate to a function takeing 1 arguments c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 Pipeline

class PipelineJob {
private:
std::thread *thread;
void execute(PipelineJob* object);
public:

void execute(PipelineJob* object)
{
}

PipelineJob()
{
this->thread = new std::thread(&PipelineJob::execute, this);
}
};

我尝试了很多变体,现在有人如何解决这个问题?

最佳答案

为简单起见,删除了模板和指针,这或多或少是您想要的:

class PipelineJob 
{
private:
std::thread thread_;
void execute(PipelineJob* object) { ..... }
public:
PipelineJob()
{
thread_ = std::thread(&PipelineJob::execute, this, this);
}
~PipelineJob() { thread_.join(); }
};

请注意,this 被两次传递给 std::thread 构造函数:一次用于成员函数的隐式第一个参数,第二次用于可见参数 成员函数的 PipelineJob* 对象

如果您的execute 成员函数不需要外部PipelineJob 指针,那么您将需要像

class PipelineJob 
{
private:
std::thread thread_;
void execute() { ..... }
public:
PipelineJob()
{
thread_ = std::thread(&PipelineJob::execute, this);
}
~PipelineJob() { thread_.join(); }
};

关于C++ 11 : Start thread with member function and this as parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718663/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com