Search code examples
c++multithreadingc++11shared-ptrstdthread

Creating an instance of shared_ptr<std::thread> with make_shared<std::thread>


Consider the following code:

class A
{
    ....
    shared_ptr<std::thread> mThread;
    void Step();
    void LaunchTrhead();
}

void A::LaunchThread()
{
    ...
    mThread=make_shared<std::thread>(Step); // This line gives an error
    ...
}

void A::Step()
{
    ...
}

I'm trying to initialise the shared pointer mThread so that it calls the function Step. However, the compiler gives me the error "invalid initialization of reference of type ... from expression of type 'unresolved overloaded function type'". Obviously I'm doing something stupid, but I can't put my finger on it. Can anybody help? Thanks in advance!


Solution

  • Step() is a non-static member function, so it has an implicit first parameter of type A*. You need to bind the current instance of A when invoking it.

    mThread = std::make_shared<std::thread>(std::bind(&A::Step, this));
    

    You can also use a lambda instead of bind

    mThread = std::make_shared<std::thread>([this]{ Step(); });
    

    As @Casey points out in the comments, std::thread's constructor has special treatment for pointer to member functions, and will assume the first following argument is a pointer or reference to the instance on which to call the member function. This means you can avoid bind and directly pass this as the second argument.

    mThread = std::make_shared<std::thread>(&A::Step, this);