How does CPP manage the life cycle of callback returned by bind?

-sharpinclude <functional>
-sharpinclude <iostream>


class Test
{
public:
      void blah() { std::cout << "BLAH!" << std::endl; }
};


int main()
{
    // store the member function of an object:
    Test test;  
    std::function< void() > callback = std::bind( &Test::blah, test );
    callback();
    // .....
}


in the above code, a member function of the object test is bound to the std::function object callback. If I store the callback somewhere else until the test object is destroyed, will it not coredump to call callback? Is the life cycle of test bound to callback (which ensures that callback is valid, after all, is bound to the member function of test)?

CPP
Jul.06,2022

std::bind will copy or move the input parameters
The arguments to bind are copied or moved, and are never passed by reference unless wrapped in std::ref or std::cref.

{
    Test* test = new Test;
    auto callback = std::bind( &Test::blah, test ); // test,test.
    delete test;
    callback(); // coredump,,.
}
{
    Test* test = new Test;
    auto callback = std::bind( &Test::blah, *test ); // test.
    delete test;
    callback(); // ,callbacktest
}
{
    auto callback = std::bind( &Test::blah, Test() ); // 
    callback(); // 
}

if you need to keep Test objects in line with the callback life cycle, consider using move (omitting one copy overhead) or unique_ptr or shared_ptr

.
Menu