代码:
// create class instance
MC_THREAD MTHR;
// set some values in the class
MTHR.setup_mc_thread("com6", &es);
// create an thread to run the non-static member function
std::thread MCTHR(MC_THREAD::start_mc_thread, std::ref(MTHR));
该函数的定义是:
void MC_THREAD::start_mc_thread(){
while(1){
//do_stuff
}
}
Windows 8&10使用基于GCC 5.1.0的TDM-GCC编译器。
以上代码在Linux上使用GCC 7.3生成以下错误:
错误:非静态成员函数的使用无效'void mc_thread :: start_mc_thread((’|
生成错误的机器使用GCC(GCC(7.3.1 20180303(红色帽子7.3.1-5(
运行Fedora 27任何建议都将不胜感激!
已解决:请参阅下面的Sam评论
也必须链接pthread。
我最初认为问题是std::reference_wrapper
的用法。但是,汇编错误实际上是由于类成员函数需要是指针。以下用GCC 7.3.1编译:
#include <thread>
#include <utility>
#include <functional>
class x {
public:
void start_thread();
};
int main()
{
x y;
std::thread thr{&x::start_thread, std::ref(y)};
}
为类成员启动线程的常用方法是将普通指针作为类实例传递。在这种情况下,这也有效:
std::thread thr{&x::start_thread, &y};
这是更常见的语法。不需要参考包装器。但是在所有情况下,第一个参数必须是指向类方法的指针。&x::start_thread
是这样的指针。x::start_thread
本身不是。那是真正的问题。
std::thread
的构造函数的参数仅指定为...
f-可呼叫的对象要在新线程中执行
您必须真正挖掘可可对象的定义。我想到的基本用法对应于在此列出的第三个选项。但是参考包装器也可以接受。但是,在所有情况下,您都必须将指针指向成员函数作为第一个参数。