Re: [Boost-users] [SmartPtr] Memory Leak Perhaps

On Monday 20 September 2010 02:44:12 pm you wrote:
Dear Benjamin,
shared_ptr to this are dangerous. As soon as you do that twice you already have a problem.
Oh, that's interesting. Could you please explain why?
Well because you can only erase 'this' once. When you have two _independent_ smart pointers, both will attempt to delete the object they're pointing to.
If you want to create shared_ptrs to this, use shared_from_this.
http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/enable_shared_from_th is.html
Thank you for the reference. At the very bottom of the documentation, I see "There must exist at least one shared_ptr instance p that owns t" (in the requirements of template<class T> shared_ptr<T const> enable_shared_from_this<T>::shared_from_this() const). So, does the following code not meet this requirement?
class Y: public T, public boost::enable_shared_from_this<Y> { public:
boost::shared_ptr<Y> f() const { return shared_from_this(); } };
const T* tp = new Y;//where Y also derives from T boost::shared_ptr<T> q = tp->f();
Yes, as far as I know this won't work. But why would you want that? boost::shared_ptr<T> q = boost::make_shared<Y>(); is the safe way to do it. No explicit 'new', no explicit 'delete', no problems. Call your insert_me_into routine through the shared_ptr. Then, inside insert_me_into, after you're done with your computations, use shared_from_this to get a shared_ptr to stick into the container.
TIA, --Hossein
HTH, Benjamin
participants (1)
-
Benjamin Sobotta