
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