Boost logo

Boost Users :

Subject: Re: [Boost-users] Problem with enable_shared_from_this and shared_ptr
From: Lars Viklund (zao_at_[hidden])
Date: 2010-08-02 02:40:58


On Thu, Jul 22, 2010 at 03:48:03PM -0400, John Dlugosz wrote:
>
> > There must be at least one shared_ptr instance that owns the object
> > that
> > you are calling shared_from_this() on. Also see the examples at the
> > above link.
> >
>
> My smart pointers, which are very similar to shared_ptr and weak_ptr, differ strongly in this respect in terms of initial concept: The "lost and found" principle allows you to obtain a smart pointer from this or other dumb pointer, and it always works, regardless of whether other smart pointers currently exist. To me, that follows from the original idea of smart pointers and multithreaded programming: you don't know who is going to be the last one out!
>
> As an early example (I published articles on the ideas in the mid '90s), it didn't stand up to standardization because it is difficult to achieve efficiently if it is non-intrusive. However, I don't see why a class that _does_ derive from the special supporting base class can't have full "lost and found" semantics, such that no special obtaining call is needed -- any smart pointer created from the object plays properly with any others that already exist. Meanwhile, those that don't derive from the special base class (non-intrusive) don't support lost-and-found and must only construct a smart pointer once.
>
> I'm sure the template metaprogramming is _much_ better now, both in technique and in what the compiler can actually swallow. So certainly the code that creates a smart pointer from a raw pointer can do one thing if T is derived from the special base class (find the existing smarts) and something else otherwise (create fresh smarts and prey that it's not been done before). I could almost do it in 1994 with badly broken templates that barely functioned for pedestrian parameterized types (had to add a line for non-intrusive types to support), but today it's no sweat to match "all types having can_handle as a base class" using enable_if, and void* for those that aren't.
>
> So, my point is that the shared_ptr can be improved in this area, without major changes.
>
> --John

Except that you lose the ability to write code like

T t;
shared_ptr<T> tp(&t, &nop_deleter);

or simply code like

T t;

if you mandate that anything that inherits enable_shared_from_this
should automagically conjure up a shared_ptr on demand.

-- 
Lars Viklund | zao_at_[hidden]

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