Sign in to follow this  
jakovo

using "this" within a shared_ptr<>

Recommended Posts

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

basically this is the code:

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

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:

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

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
TheUnbeliever    963
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
Antheus    2409
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this