如何正确地将此指针传递给 std::thread

How do I properly pass this pointer to std::thread

本文关键字:std thread 指针 正确地      更新时间:2023-10-16

ALL,

在我的班级里.cpp

MyClass::Initialize()
{
    m_thread = new std::thread( &Foo::func, *this );
}

在foo.cpp:

void Foo::func(MyClass &obj)
{
    // some processing
    // which involves modifying `obj`
}

我在 gcc 上收到编译器错误:

error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Foo::*)(MyClass&)>(Foo*, MyClass)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^

啪!

为了调用Foo::func,它需要一个类型为 Foo 的对象来调用它。所以你必须问自己,func实际上需要是一个成员函数,还是一个非静态函数?如果你有一个Foo对象要用来调用它,你可以把它作为第二个参数传递。

至于第三个,你会传递*this,但由于std::thread复制了它的每个参数,你需要使用引用包装器并以这种方式传递它:

m_thread = new std::thread( &Foo::func, foo, std::ref(*this) );