|
Boost Users : |
Subject: Re: [Boost-users] intrusive_ptr vs shared-ptr
From: Edward Diener (eldiener_at_[hidden])
Date: 2013-01-22 22:06:38
On 1/22/2013 3:46 AM, John M. Dlugosz wrote:
>
>> Well I wouldnt say these items are 'marginal', because most come from
>> real life scenarios. You can work around things but it is always that
>> u have to remember that there were some boundary cases with
>> shared_ptr. It took me some time to convince my colleagues to swap
>> from raw pointers to shared pointers and having some boundary cases
>> doesn't help then. I still prefer shared pointers, but I am not sure
>> if all in all they would be better than e.g. intrusive_ptr's with ref
>> counting (even without lacking the weak_ptr feature). Note that i look
>> upon this from a client perspective (i.e. large data acquisition
>> application), not from a library builder perspective.
>
> I really miss having a "lost and found" feature, which (in the late
> 90's) I wrote about as being one of the six essential features of my
> smart pointer design. That is, given a raw pointer p that is already
> known to the smart pointer system, creating another smart pointer from p
> will work in harmony with them, NOT break it. I've repeatedly come
> across code that hooks up objects with other objects in the constructor
> and I've had to work-around that in various ways, usually by adding a
> Create wrapper that finishes the work, and sometimes fiddling more than
> I would have wanted to with the design. I've also found cases where it
> is really annoying not knowing whether another smart pointer has already
> been created yet for the object.
The way I found to do this is to have an object created through a smart
pointer participate in a two-phase creation process. The first phase is
some constructor and the second phase is some sort of initialization
member function, which I usually call Init of the form 'void Init()'. In
the Init member function, use shared_from_this() to create a weak_ptr to
the object's smart pointer as a private member data variable. Then add a
member function, which I usually call ToPtr, which returns the object as
a smart pointer using the private member data function by calling Lock
on the weaK_ptr.
Now if you have a raw pointer to the object you can call it's ToPtr
member function to get its smart pointer.
You need the two-phase creation process because you cannot use
shared_from_this() until the object is fully constructed.
I do not know how closely this mimics your "lost and found" feature but
it enables you to get a smart pointer from a raw pointer of the same
type. Of course your object must always intially be created as a smart
pointer, which means it must always be dynamically allocated.
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