boost shared_from_this<>()

Viewed 20491

could someone summarize in a few succinct words how the boost shared_from_this<>() smart pointer should be used, particularly from the perspective of registering handlers in the io_service using the bind function.

EDIT: Some of the responses have asked for more context. Basically, I'm looking for "gotchas", counter-intuitive behaviour people have observed using this mechanism.

5 Answers

Stuff is missing from some of the comments above. Here's an example that helped me:

Boost enable_shared_from_this example

For me, I was struggling with errors about bad weak pointers. You HAVE to allocate your object in a shared_ptr fashion:

class SyncSocket: public boost::enable_shared_from_this<SyncSocket>

And allocate one like this:

boost::shared_ptr<SyncSocket> socket(new SyncSocket);

Then you can do things like:

socket->connect(...);

Lots of examples show you how to use shared_from_this() something like this:

boost::asio::async_read_until(socket, receiveBuffer, haveData,
        boost::bind(&SyncSocket::dataReceived, shared_from_this(), boost::asio::placeholders::error));

But was missing for me was using a shared_ptr to allocate the object to begin with.

Related