如何将实例成员函数作为回调传递给std :: thread

时间:2013-01-22 07:12:03

标签: c++ lambda function-pointers

  

可能重复:
  Start thread with member function

我对C ++很陌生。我的经验主要是使用javascript和java。

我在Lion上使用Xcode。下面的代码给了我一个编译错误“必须调用对非静态成员函数的引用;你的意思是不带参数调用它吗?”

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread(handler);
    }
};

我还尝试了this->handler&handler和其他变体,但都没有奏效。此代码编译并完成我想要的内容:

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread([this]() {
            handler();
        });
    }
};

为什么我不能传递对成员函数的引用?我的工作是最好的解决方案吗?

3 个答案:

答案 0 :(得分:10)

std::thread myThread(&MyClass::handler, this);
myThread.join();

答案 1 :(得分:4)

如果您不想使用lamda,可以使用std::mem_fun

你能做到吗?

std::thread myThread(std::mem_fun(&MyClass::handler),this);

std::thread接受函数的参数(这是第一个参数),this作为参数传递给mem_fun对象,然后在{{1}上调用处理函数}}

您也可以简单地执行以下操作,礼貌 - Start thread with member function

this

答案 2 :(得分:4)

使用lambda访问成员函数中的类成员,您需要捕获this。以下代码中必须使用[this]

void handleThings() 
{
    std::thread myThread([this]() {
        handler();
    });
}

您可以通过引用捕获this,但它不如按值捕获它有效。因为通过引用需要双间接(模数编译器优化)

void handleThings() {
        std::thread myThread([&]() {
            handler();
        });
    }

Lambdas通常是比bind更好的选择。

  • 读者更容易理解。
  • 效率更高。