$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
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