Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does shared_from_this in std::bind work where object does not exist?

Is that code safe?

class C : public std::enable_shared_from_this<C> {
    void start() {
             boost::asio::async_write(socket_, boost::asio::buffer(message_), 
             std::bind(&tcp_connection::handle_write, shared_from_this(),
             _1, _2));
    };
    // ...
};

class D {
    void start()
    {
         std::shared_ptr<C> cptr = std::make_shared<C>(); // (1)
         cptr->start();
    } // (2)
};

If the message is long, the async_write operation can take a long time.

There is only one shared_ptr pointing to the C object at point (1). start() is called, start() finishes and at (2) the variable cptr goes out of scope and is destroyed.

When async_write has finished the writing operation, the callback is called; this causes a crash because shared_from_this() tries to make a shared_ptr to a non-existent object.

Is this description of what would happen correct?

like image 954
peter55555 Avatar asked Jan 29 '26 05:01

peter55555


1 Answers

No, you are not right.

The call to shared_from_this() happens before start returns. A copy of the resulting shared_ptr is held by the result of bind.

So when you reach (2) only one of the two references to the object has gone, and it remains alive

like image 111
Alan Stokes Avatar answered Jan 30 '26 19:01

Alan Stokes