
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-t... Sent from the Boost - Users mailing list archive at Nabble.com.

sorry - i found it in the documentation. I thought the problem was in creating the pointer, but it was in the cyclic nature of the parent/child relationship. for reference, it's in the docs on shared_ptr at http://www.boost.org/doc/libs/1_45_0/libs/smart_ptr/shared_ptr.htm "Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. For example, if main() holds a shared_ptr to A, which directly or indirectly holds a shared_ptr back to A, A's use count will be 2. Destruction of the original shared_ptr will leave A dangling with a use count of 1. Use weak_ptr to 'break cycles.'" -- View this message in context: http://boost.2283326.n4.nabble.com/memory-leak-when-using-shared-from-this-t... Sent from the Boost - Users mailing list archive at Nabble.com.
participants (1)
-
jochemspek