|
Re: Is intrusive_ptr the thing to use?: msg#00291lib.boost.user
From: "Hickman, Greg" <greg.hickman@xxxxxxxx> > I need an object managed through a shared_ptr to be able to pass itself > (i.e., this) to another object which also expects a shared_ptr. Is there a > preferred implementation technique for this when using the boost smart > pointers? Yes, there is now. The possible solutions depend on the location where you want to extract a shared_ptr to 'this'. If you need to do this in the constructor, use a static factory function: class X { private: X(); public: static shared_ptr<X> create() { shared_ptr<X> px(new X); // do something with px return px; } }; If you need to obtain a shared_ptr to this in a nonvirtual member function X::f, consider replacing it with a free function: void f(shared_ptr<X> this_, ...); If 'f' is virtual, have the object store a weak_ptr to itself: class X { private: weak_ptr<X> weak_this; X(); X(X const &); X& operator=(X const &); public: static shared_ptr<X> create() { shared_ptr<X> px(new X); px->weak_this = px; return px; } shared_ptr<X> shared_from_this() { shared_ptr<X> px(weak_this); return px; } shared_ptr<X const> shared_from_this() const { shared_ptr<X const> px(weak_this); return px; } }; The current CVS version of shared_ptr includes explicit support for this idiom, a base class template enable_shared_from_this<> that supplies the shared_from_this member function. It's even documented. ;-) > I think I've seen conversation in the past about deriving from > boost::counted_base and calling shared_from_this(), but I think I also > remember seeing comments to the effect that this is going away. Yes, you are right. This is going away. ------------------------ Yahoo! Groups Sponsor ---------------------~--> Get 128 Bit SSL Encryption! http://us.click.yahoo.com/CBxunD/vN2EAA/xGHJAA/EbFolB/TM ---------------------------------------------------------------------~-> Info: <http://www.boost.org> Wiki: <http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl> Unsubscribe: <mailto:boost-users-unsubscribe@xxxxxxxxxxxxxxx> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: solaris gcc 3.2 stlport regexp (bug?): 00291, c_twiner |
|---|---|
| Next by Date: | Re: Link problem with boost::signals and console applications in MS Visual C++ 6 / Windows: 00291, Douglas Gregor |
| Previous by Thread: | Re: Is intrusive_ptr the thing to use?i: 00291, Stephen Crowley |
| Next by Thread: | RE: Is intrusive_ptr the thing to use?: 00291, Mark Storer |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |