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.
shared_from_this<>
is used if an object wants to get access to ashared_ptr<>
pointing to itself.Usually an object only knows about the implicit
this
pointer, but not about anyshared_ptr<>
managing it. Also,this
cannot easily be converted into ashared_ptr<>
that shares ownership with other existingshared_ptr<>
instances, so there is no easy way for an object to get a validshared_ptr<>
to itself.shared_from_this<>
can be used to solve this problem. For example:the
boost::asio::io_service
destructor documentation explains it fairly wellTypically your objects will chain asynchronous operations where the handlers are bound to member functions using
boost::bind
andboost::shared_from_this()
. There are some examples that use this concept.The biggest "gotcha" I've run into is that it's illegal to call shared_from_this from the constructor. This follows directly from the rule that a shared_ptr to the object must exist before you can call shared_from_this.
From my understanding, sometimes in your code you want a class to offer up
shared_ptr
's to itself so that other parts of your code can obtain shared_ptr's to an object of your class after it has been constructed.The problem is that if your class just has a
shared_ptr<>
to itself as a member variable, it will never get automatically destructed, since there is always "one last reference" hanging around to itself. Inheriting fromenable_shared_from_this
gives your class an automatic method which not only returns ashared_ptr
, but only holds a weak shared pointer as a member variable so as not to affect the reference count. This way, your class will be freed as usual when the last reference to it is gone.I've never used it, but this is my understanding of how it works.