Boost logo

Boost Users :

Subject: [Boost-users] memory leak when using shared_from_this
From: jochemspek (spam_at_[hidden])
Date: 2011-01-12 11:19:20


hi there,

I'm having trouble understanding the cause of a memory leak apparently
caused by using 'shared_from_this'.
The following is the case: I have a AbstractProperty class with XMLNode as
subclass. there exist two typedefs for these classes, namely typedef
shared_ptr< XMLNode > XMLNodePtr and similar for AbstractProperty. in the
XMLNode class I have the member function 'addChild' that adds a child to the
XMLNode instance. I keep a reference to the parent by calling
chid->setParent(), *with a shared pointer to this*. This results in a (quite
severe) memory leak. I can resolve the problem by using a shared_ptr with a
null-deleter ( see f.e. http://lists.boost.org/boost-users/2008/05/36281.php
), but I don't quite understand *why* the leak occurs, as I understand it so
that the shared_from_this is a weak_ptr to this. I would much appreciate any
comments.

thanks,

Jochem
//---------------------------begin code-----------------------------
const XMLNodePtr XMLNode::addChild( const string name ){
        XMLNodePtr child( new XMLNode() );
        child->setParent( static_pointer_cast< XMLNode, AbstractProperty >(
shared_from_this() ) );
        m_children.push_back( child );
        return( child );
}
//---------------------------end code-----------------------------

-- 
View this message in context: http://boost.2283326.n4.nabble.com/memory-leak-when-using-shared-from-this-tp3214313p3214313.html
Sent from the Boost - Users mailing list archive at Nabble.com.

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net