繁体   English   中英

无效使用非静态成员函数C ++线程Linux

[英]Invalid use of non-static member function c++ thread linux

我尝试运行一个函数,该函数启动线程,但是我收到错误消息:

error: invalid use of non-static member function ‘void Sniffer::f1(int)’

码:

#include "library.hpp"

class Sniffer
{
    void f1( int x );
    void f2();
};

void Sniffer::f1( int x )
{
    while (true)
    {
        sleep(x);
        std::cout << 1 << std::endl;
    }
}

void Sniffer::f2()
{
    int y = 5;
    std::thread t1( f1, y );
    t1.join();
}

int main()
{
    return 0;
}

还有其他方法可以在不更改功能的情况下在静态功能上进行修复吗?

在C ++中,成员函数具有绑定到this的隐式第一个参数。 创建线程时,必须传递this指针。 您还必须使用类名称限定成员函数。 在您的情况下,正确的线程构造函数将如下所示:

std::thread t1( &Sniffer::f1, this, y );

或者,您可以改为将lambda传递给线程构造函数:

std::thread t1([this, y] // capture the this pointer and y by value
{
    this->f1(y);
});

当您创建std::thread它不会为您捕获this指针。 创建线程时,必须包含this指针,或者可以使用lambda来捕获this或通过引用捕获所有内容。

例如:

void Sniffer::f2()
{
    int y = 5;
    std::thread t1(&Sniffer::f1, this, y);
    t1.join();
}

要么:

void Sniffer::f2()
{
    int y = 5;
    std::thread t1([&,y](){f1(y); });   // captures everything (including this) by reference, captures a copy of y
                                        // becuase y coud go out of scope and be destroyed while the thread could 
                                        // continue running (even though in this case that won't happen because the join is in the same scope
    t1.join();
}

当然,如果您捕获了this则无需在lambda主体中提及它,并且不需要参数,我们可以删除()简化为:

void Sniffer::f2()
{
    int y = 5;
    std::thread t1([this,y]{f1(y); }); 
    t1.join();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM