C++11 线程 - 非静态成员函数的无效使用 - 工作 gcc 5.1.0 损坏的 gcc 7.3.1

标签 c++ c++11 compiler-errors stdthread

代码:

    // 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
        }
    } 

以上代码使用基于 gcc 5.1.0 的 TDM-GCC 编译器在 Windows 8 和 10 上编译(并正常工作)。

上面的代码在 linux 上使用 gcc 7.3.1 生成以下错误:
错误:无效使用非静态成员函数‘void MC_THREAD::start_mc_thread()’|

产生错误的机器正在运行 fedora 27 using gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)

如有任何建议,我们将不胜感激!

已解决:请参阅下方 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 构造函数的参数 is specified merely as...

f - Callable object to execute in the new thread

你必须真正深入研究the definition of a callable object .我想到的基本用法对应于此处列出的可调用对象的第三个选项。但是引用包装器也是可以接受的。但是,在所有情况下,您都必须将指向成员函数的指针作为第一个参数。

关于C++11 线程 - 非静态成员函数的无效使用 - 工作 gcc 5.1.0 损坏的 gcc 7.3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49685127/

相关文章:

c++ - 如何在另一个类中使用主类中的全局 const int 变量

c++ - 将 RFC 822 时间戳转换为 unixtime,时区值不起作用,C/C++

c++ - std::round 不是 std on android 的成员

c++11 - clang 链接错误 : DSO missing

c++ - 我的小型转储变得太大而无法被 Visual Studio 加载,我该如何解决这个问题?

c++ - 迭代器元组。运算符++的实现

c++ - initializer_list 作为数组引用参数的参数?

c++ - 将数据从一个文件复制和粘贴到另一个文件时出错

Java编译器错误谜题: "inner classes cannot have static declarations" - except for simple types

java - 部分数组错误