Use a shared_ptr as a 'backpointer'?
I run into situations where it's useful for an object to have a 'backpointer' to the object instance that created it (example below). Is there a pattern/idiom for doing this using shared_ptr? Or maybe I need to re-think the idea of the backpointer in the first place? class Bar; class Foo { public: Foo(Bar* b) : p(b){} private: Foo() : p(0){} shared_ptr<Bar> p; } class Bar { void doit() { new Foo(???); // <<< new Foo(this) obviously won't work. } }
I run into situations where it's useful for an object to have a 'backpointer' to the object instance that created it (example below). Is there a pattern/idiom for doing this using shared_ptr? Or maybe I need to re-think the idea of the backpointer in the first place?
class Bar; class Foo { public: Foo(shared_ptr<Bar>); private: shared_ptr<Bar> p; }; class Bar : boost::shared_count { void doit() { new Foo(boost::shared_from_this(this)); // <<< new Foo(this) obviously won't work. } }; HTH, Dave -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave@boost-consulting.com * http://www.boost-consulting.com
"David Abrahams"
wrote in message news:OF699D7956.EED22A4F-ON88256C43.00722AD0@tais.net... I run into situations where it's useful for an object to have a 'backpointer' to the object instance that created it (example below). Is there a pattern/idiom for doing this using shared_ptr? Or maybe I need to re-think the idea of the backpointer in the first place?
class Bar;
class Foo { public: Foo(shared_ptr<Bar>);
private: shared_ptr<Bar> p; };
class Bar : boost::shared_count { void doit() { new Foo(boost::shared_from_this(this)); // <<< new Foo(this) obviously won't work. } };
But shared_count is in detail nemespace. Is it correct ? regards, bohdan
participants (3)
-
Bohdan
-
David Abrahams
-
dick.bridges@tais.com