Jump to content
  • Advertisement
Sign in to follow this  
jakovo

using "this" within a shared_ptr<>

This topic is 2272 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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!