using "this" within a shared_ptr<>

Started by
2 comments, last by Antheus 11 years, 10 months ago
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"
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]
[TheUnbeliever]
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"
Pass shared_ptr by reference as well. Otherwise, reference counter is modified each time a function is called, despite ownership not being changed.

This topic is closed to new replies.

Advertisement