Boost logo

Boost :

Subject: [boost] [shared_ptr] enable_shared_from_any ?
From: Philip Warner (pjw_at_[hidden])
Date: 2010-05-15 08:28:12


Many apologies if this has already been debated and discarded, but I
have been using boost for a little while now, and most specifically
boost::shared_ptr. I recently found enable_shared_from_this{2} and, in
SVN, enable_shared_from_raw, and while both of these are extremely
useful, ISTM they do not go quite far enough.

Specifically, what I would like to see is a solution to the following code:

     C1 *p = new C1();
    shared_ptr<C1> ptr(p);
    ...
    ...some time later....
    shared_ptr<C1> ptr2<p>;

and the resulting mess because of double-deallocation. Yes, one solution
id discipline, but for a library developer, a better solution might be
robustness in the face of (mild) ignorance or misuse.

And yes, this is sloppy, but in our case we have a set of interfaces
that want to implement variant function return types based on derived
class pointers, and we can not do that by returning shared_ptr objects.
We need to return raw pointers, then rewrap them.

One solution is shared_from_this etc.

Another is to extend shared_from_this so that *any* shared_ptr created
from and object that inherits, say, enable_shared_from_any, will always
get a shared pointer that works as one might expect.

To this end we have built a (trivial) class that inherits from
shared_ptr<T> and a matching base class, that together function to
achieve what we need. The only real problem is we have to duplicate some
parts of shared_ptr (constructors and operators mainly), the second
problem is that not being experts in the very fine details of templates,
boost, and cross-platform development, it would be extremely convenient
if this functionality were implemented within shred_ptr in a similar way
to the way enable_shared_from_this is done -- ie. only for those classes
that implement an appropriate base class. The third problem is that
because it does not have access to shared_ptr internals, it is not as
efficient as it might be.

Is submitting a patch to shared_ptr the appropriate way forward? Has
this been discussed, debated and discarded before?

If there is interest I am very happy to submit a patch, and I would also
welcome any pointers (no pun intended) as to where the disadvantages and
advantages of this kind of approach have been discussed before.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk