{ Reformatted; please, pretty please with sugar on top, limit your
lines to 70 characters - mod }
On Wednesday, October 17, 2012 11:30:02 PM UTC+1,
isk...@googlemail.com wrote:
> I found that enable_shared_from_this is not only restricting way of
> creating instance of a class but also leads to obscure design. Usual
> way of using it is when class has some active object and passes self
> reference to it to listen notification from this object. First of
> all this can be always refactored using pimpl idiom (create
> shared_ptr <ListenerImpl>(new ListenerImpl(this)) and pass pimpl
> reference to active object. It makes intention clear. One more
> benefit is that this approach doesn't restrict possible ways of
> creation.
I don't see how this works. Say I have a class Foo. Objects of this
class are owned by shared_ptrs. If I want to pass a shared ptr to
some part of Foo into a listener (and I want the listener to keep my
Foo alive), how would constructing a separate shared_ptr help? I want
a single reference count, and only when this reaches zero, do I want
the object to disapper.
> The problem with enable_share_from_this is that designer of a class
> should provide factory method which returns shared_ptr and this
> should be the only way to create instance of the class. But this
> never happens - nobody does it! I have an application where the
> factory function needs to be a member of another class. I could
> make the creating class a friend of the created, or I could create
> another factory function, but it really doesn't seem worth it. I'm
> just not that worried about people creating objects of my class on
> the stack.
> It's very easy to overlook enabled_shared_from_this in inheritance
> list or just forget about its restriction and create instance on
> stack.
That hasn't been my experience. Wherever I have used shared_ptr it
has been the case that *every* instance of the class is controlled by
a shared_ptr. It just wouldn't make sense to create one on the stack.
> So why should somebody use enable_shared_from_this?
Err. Whenever the class is expected to be owned by a set of
shared_ptrs, and the class wants to provide a shared_ptr to itself,
either as an argument to a function, or as a return value.