本文介绍了如何将实例成员函数作为回调传递给std :: thread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C ++的新手.我的经验主要是使用javascript和Java.
I'm VERY new to C++. My experience has mostly been with javascript and java.
我在Lion上使用Xcode.以下代码为我提供了一个编译错误:必须调用对非静态成员函数的引用;您的意思是不带任何参数调用它吗?"
I'm using Xcode on Lion. The following code gives me a compilation error "Reference to non-static member function must be called; did you mean to call it with no arguments?"
class MyClass {
private:
void handler() {
}
public:
void handleThings() {
std::thread myThread(handler);
}
};
我也尝试了this->handler
,&handler
和其他变体,但没有一个起作用.这段代码可以编译并完成我想要的:
I also tried this->handler
, &handler
, and other variations, but none of them worked. This code compiles though and accomplishes what I want it to:
class MyClass {
private:
void handler() {
}
public:
void handleThings() {
std::thread myThread([this]() {
handler();
});
}
};
为什么不能将引用传递给成员函数?我的解决方法是最好的解决方案吗?
Why can't I pass a reference to a member function? Is my work-around the best solution?
推荐答案
std::thread myThread(&MyClass::handler, this);
myThread.join();
这篇关于如何将实例成员函数作为回调传递给std :: thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!