Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


using "this" within a shared_ptr<>


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Jake Rivers   Members   -  Reputation: 338

Like
0Likes
Like

Posted 26 May 2012 - 08:33 PM

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!
"lots of shoulddas, coulddas, woulddas in the air, thinking about things they shouldda couldda wouldda donne, however all those shoulddas coulddas woulddas ran away when they saw the little did to come"

Sponsor:

#2 TheUnbeliever   Members   -  Reputation: 961

Like
1Likes
Like

Posted 26 May 2012 - 08:48 PM

Derive CNode from enable_shared_from_this, do pChild->OnAttach(shared_from_this());
[TheUnbeliever]

#3 Jake Rivers   Members   -  Reputation: 338

Like
0Likes
Like

Posted 26 May 2012 - 09:28 PM

Ah!.. perfect!

Thank you TheUnbeliever!...
"lots of shoulddas, coulddas, woulddas in the air, thinking about things they shouldda couldda wouldda donne, however all those shoulddas coulddas woulddas ran away when they saw the little did to come"

#4 Antheus   Members   -  Reputation: 2397

Like
1Likes
Like

Posted 27 May 2012 - 05:58 AM

Pass shared_ptr by reference as well. Otherwise, reference counter is modified each time a function is called, despite ownership not being changed.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS