Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-10-14 08:02:25


Dragan Milenkovic wrote:
> Hello, people,
>
> I've been using enable_shared_from_this a LOT, mostly for implementing
> the Observer pattern (an object holds a list of weak pointers to it's
> observers).
>
> I wanted to know why are shared_from_this member functions public
> instead of being protected?

No particular reason. Both public and protected seem equally good to me.

> Also, I've used the following expression a few times:
>
> shared_polymorphic_cast<This>(shared_from_this())
>
> Any thoughts on putting it inside the enable_shared_from_this...
> shared_from_base<This>() or polymorphic_shared_from_this<This>() or
> such?

It is usually best to keep the interface minimal but complete, unless an
operation is so frequent that everyone ends up reinventing the same wheel.
The envisioned use of enable_shared_from_this is as a base of the leaf
class, so no explicit cast should be needed.

The cast is only necessary if you introduce enable_shared_from_this
somewhere in the middle of a hierarchy.

> Also, any comments on the designs I used? Better observers?

It is hard to say; you'll need to go into more detail about the observers.
If they are only notified on destruction of the observed entity, the typical
shared_ptr approach is to reverse/eliminate the dependency and make the
observers store weak pointers to the "observee".

For other notification scenarios, there is the usual tradeoff between
polling and messaging. I prefer polling most of the time since this
eliminates the need to store an observer list and makes it possible to
"observe" classes that weren't specifically designed for this, but there may
be a performance cost.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net