Boost logo

Boost Users :

From: Eric Niebler (eric_at_[hidden])
Date: 2005-03-24 16:50:43


edA-qa mort-ora-y wrote:

> 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
> ///////////////////////////////

You want to use enable_shared_from_this:

/////////////////////////////
class A : enable_shared_from_this<A> {
     void Do( shared_ptr<B> b )
         { b->Add( shared_from_this() ); }
}

class B {
     vector<shared_ptr<A> > items;
     void Add( shared_ptr<A> a )
         { items.push_back( a ); }
}

...
shared_ptr<A> a( new A() );
shared_ptr<B> b( new B() );

a->Do( b ); // OK !

You can read about enable_shared_from_this in the shared_ptr docs.

-- 
Eric Niebler
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