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 am trying to initialize a generic mThread pointer so that it calls the Step function. However, the compiler gives me the error "incorrect initialization of a type reference ... from an expression of the type" unresolved overloaded function type "". Obviously, I'm doing something stupid, but I can't put it on him. Can anyone help? Thanks in advance!

+4
source share
3 answers

Step() - -, A*. A .

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

bind

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

@Casey , std::thread - - , -. , bind this .

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

labda :

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

, , -.

, -, , .

, void Step() :

mThread=make_shared<std::thread>(::Step()); 

:: .

+1

You should use shared_from_this()replace this

0
source

Source: https://habr.com/ru/post/1526954/


All Articles