将类的成员函数传递给std :: thread

Dra*_*gon 6 c++ multithreading c++11

我在我的代码中使用std :: thread时遇到问题:

Class Timer
{
...
public:
    void Start(bool Asynch = true)
    {
        if (IsAlive())
        {
            return;
        }
        alive = true;
        repeat_count = call_number;
        if (Asynch)
        {
            t_thread = std::thread(&ThreadFunc, this);
        }
        else
        {
            this->ThreadFunc();
        }
    }
    void Stop()
    {
        alive = false;
        t_thread.join();
    }
...
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

错误C2276:'&':对绑定成员函数表达式的非法操作

t_thread是类的私有std :: thread实例,ThreadFunc()是返回void的类的私有成员函数;

我想我明白有两种方法可以将成员函数发送到std :: thread,如果函数是静态的,我会使用t_thread = std :: thread(threadfunc); 但我不希望ThreadFunc是静态的,这样做会给我带来错误.

我想我通过创建另一个函数解决了这个问题:

std::thread ThreadReturner()
{
    return std::thread([=] { ThreadFunc(); });
}
...
t_thread = ThreadReturner();
Run Code Online (Sandbox Code Playgroud)

这样我就不会出错,但我不明白为什么第一个不起作用.

任何帮助表示赞赏.

我的问题看起来像副本,但只有一个区别,在另一个问题的答案中,std :: thread在类声明或实现之外使用,它在main()中,在这种情况下指定范围对我有意义,但是当在类内部调用std :: thread时没有.这是我看到的唯一区别以及为什么我制作这个帖子,抱歉可能重复.

Som*_*ken 6

您应该指定范围

&Timer::ThreadFunc
Run Code Online (Sandbox Code Playgroud)