How to pass instance member function as callback to std :: thread

Possible duplicate:
Start Stream Using Member Function

I am VERY new to C ++. My experience was mainly with javascript and java.

I am using Xcode on Lion. The following code gives me a compilation error. "A reference to a non-stationary member function must be called, did you mean to name it without arguments?"

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

I also tried this->handler , &handler and other options, but none of them worked. This code compiles and does what I want:

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

Why can't I pass a link to a member function? Am I working on a better solution?

+4
source share
3 answers
 std::thread myThread(&MyClass::handler, this); myThread.join(); 
+6
source

You can use std::mem_fun if you do not want to use lamda.

Can you do it?

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

std::thread takes the arguments of the function (which is the first argument) and this is passed as an argument to the mem_fun object, which then calls the handler function on this .

You can also just do below, kindly - Start a thread with a member function

 std::thread myThread(&MyClass::handler,this); 
+4
source

Use lambda to access class members within a member function, you need to write this . [this] is required in the following code:

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

You can write this by reference, but this is not as efficient as capturing by value. because it takes a double indirect to go through the link (optimization modulo the compiler)

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

Lambdas are usually a better choice than bind .

  • It’s easier for readers to understand.
  • More efficient.
+4
source

All Articles