Search code examples
c++c++11stdthread

Invoking a member function in a new-ed object with C++0x std::thread


I want to do something like this:

class A {
public:
    void a_start () {
        // somewhere in A: my_b = new B();
        std::thread t(my_b->b_start);   // won't compile
    }

private:
    B* my_b;
};

class B {
public:
    void b_start();
};

But it won't compile. I tried to look at http://accu.org/index.php/journals/1584 but it did not mention the case where the member function lies in a new-ed object. What is the correct syntax?


Solution

  • There are lots of ways to accomplish this, such as using std::bind or using a trampoline member function, but I'd probably just use a lambda, like this:

    std::thread t([&](){my_b->b_start();});