|
Boost Users : |
From: David Abrahams (dave_at_[hidden])
Date: 2005-03-24 16:53:42
edA-qa mort-ora-y <eda-qa_at_[hidden]> writes:
> I am in the process of converting a library of ours (which used a
> Refcounting mechanism for shared objects) to be buildable on top of the
> boost smart_ptr library*.
>
> What feature I am having the most difficulty with is the ability for an
> object to refer to itself and be properly shared. That is, by quick
> example:
>
> /////////////////////////////
> class A {
> void Do( B* b )
> { b->Add( this ); } //trouble line
> }
>
> class B {
> vector::shared_ptr<A> items;
> void Add( A* a )
> { items.push_back( a ); }
> }
>
> ...
> shared_ptr<A> a( new A() );
> shared_ptr<B> b( new B() );
>
> a->Do( b ); //hidden problems
> ///////////////////////////////
>
> In the trouble line I am having a problem since I need to refer to this,
> but it will not be referring to the shared_ptr wrapper on the object.
> Thus it will end up being delete'd twice.
Have a look at enable_shared_from_this:
http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html
HTH,
-- Dave Abrahams Boost Consulting www.boost-consulting.com
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