• Advertisement
Sign in to follow this  

using "this" within a shared_ptr<>

This topic is 2100 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, I'm doing a tree with shared_ptr<>'s to handle each node's relationship.

basically this is the code:


void CNode::AttachChild( shared_ptr<CNode> pChild )
{
pChild->OnAttach( this );
OnAttachChild( pChild );
}


If "this" is a pure pointer, and passing it as a parameter to other objects then shared_ptr<> would lose track of the actual references this pointer has.

However, if I use:


void CNode::AttachChild( shared_ptr<CNode> pChild )
{
pChild->OnAttach( shared_ptr<CNode>( this ) );
OnAttachChild( pChild );
}


this would create two actual shared_ptr<> objects tracking separately the same object (which would be VERY dengerous)...

so, how would be the proper way to use the actual shared_ptr<> that is handling "this" object?

Thanks!

Share this post


Link to post
Share on other sites
Advertisement
Derive [font=courier new,courier,monospace]CNode[/font] from [font=courier new,courier,monospace]enable_shared_from_this[/font], do [font=courier new,courier,monospace]pChild->OnAttach(shared_from_this());[/font]

Share this post


Link to post
Share on other sites
Pass shared_ptr by reference as well. Otherwise, reference counter is modified each time a function is called, despite ownership not being changed.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement