Boost logo

Boost :

Subject: Re: [boost] [shared_ptr] enable_shared_from_any ?
From: Philip Warner (pjw_at_[hidden])
Date: 2010-05-18 09:12:51


On 18/05/2010 10:22 PM, Stewart, Robert wrote:
> I don't see how inheriting from a special base class helps. Instantiating instances of a special type is no safer than calling a different function for this purpose. The issue is merely one of supplying external knowledge that the new shared_ptr should not assume sole ownership of the raw pointer. enable_shared_from_this was created to express a special use case of, as you point out, a more general need.
>

I have probably complicated matters by describing the second-best
solution we have adopted, rather than just submitting the patch (which I
have subsequently done in a later post). Please just ignore my
unnecessary digression.

The later post implements enabled_shared_from_any, which is even more
general than enable_shared_from_this.

It allows us to return raw pointers to variant types from a class
defined in a library, that have been wrapped by shared pointers in the
library, and further allows the caller to re-wrap these objects in
shared pointers, all without risking double-deallocation.

An example might help; we have

class A;
class B : class A;

class SomeOtherBase {
    virtual A* getThing();
}

class SomeOtherDerived : class SomeOtherBase {
    virtual B* getThing();
}

internally, the library that provides SomeOtherBase and SomeOtherDerived
can use shared_ptrs to wrap these objects internally, can also return
covariant function results and the caller can then wrap the resulting
pointer in a shared_ptr safely.

Also, as noted in my later post, the implementation can easily be
modified to provide the entire functionality of enable_shared_from_this[2].

In our application a very large chunk of the code only cares about the
base classes (A and SomeOtherBase), but a small and important part wants
to know about the derived types so returning variant function results is
important to us.

I hope I have not just made matters less clear!
 


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