boost shared_from_this<>()
shared_from_this<>
is used if an object wants to get access to a shared_ptr<>
pointing to itself.
Usually an object only knows about the implicit this
pointer, but not about any shared_ptr<>
managing it. Also, this
cannot easily be converted into a shared_ptr<>
that shares ownership with other existing shared_ptr<>
instances, so there is no easy way for an object to get a valid shared_ptr<>
to itself.
shared_from_this<>
can be used to solve this problem. For example:
struct A : boost::enable_shared_from_this<A> {
server *io;
// ...
void register_self() {
io->add_client(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 from enable_shared_from_this
gives your class an automatic method which not only returns a shared_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.
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.