B
Bonzo
Another smart pointer problem. I have a tree structure. The idea is for
parents to have SmartPtr's to the children, with children holding a weak
pointer (WeakPtr) back to the parent. That's great, but how do I
implement the link from child to parent?
Here's where the problem occurs:
SmartPtr<ContainerNode>
ContainerNode :: CreateChildContainer()
{
SmartPtr<ContainerNode> child( new ContainerNode );
// a) This would cause 'this' to be deallocated at end of scope!
// SmartPtr<ContainerNode> smart( this );
// child->SetParent( smart );
// b) Can't assign raw ptr to WeakPtr in SetParent.
// child->SetParent( this );
return child;
}
So how do I pass 'this' to the child? A hack to bump up the strong ref
count in case a) so SmartPtr won't deallocate 'this'? Ugh.
Instead, the calling code could of course say:
SmartPtr<ContainerNode> parent;
SmartPtr<ContainerCode> child;
....
child = parent->CreateChildContainer();
child->SetParent( parent );
and it would work fine. The WeakPtr can be assigned to from the
SmartPtr. But the caller shouldn't have to do that.
Or am I wrong in assuming I shouldn't be putting raw pointers into weak
pointers? WeakPtr::getPtr() would return NULL since there'd never be a
strong ref to the ptr.
This seems like a ridiculous thing to be stumbling on, but I'm not sure
what to do. Thanks for any help.
-jim
parents to have SmartPtr's to the children, with children holding a weak
pointer (WeakPtr) back to the parent. That's great, but how do I
implement the link from child to parent?
Here's where the problem occurs:
SmartPtr<ContainerNode>
ContainerNode :: CreateChildContainer()
{
SmartPtr<ContainerNode> child( new ContainerNode );
// a) This would cause 'this' to be deallocated at end of scope!
// SmartPtr<ContainerNode> smart( this );
// child->SetParent( smart );
// b) Can't assign raw ptr to WeakPtr in SetParent.
// child->SetParent( this );
return child;
}
So how do I pass 'this' to the child? A hack to bump up the strong ref
count in case a) so SmartPtr won't deallocate 'this'? Ugh.
Instead, the calling code could of course say:
SmartPtr<ContainerNode> parent;
SmartPtr<ContainerCode> child;
....
child = parent->CreateChildContainer();
child->SetParent( parent );
and it would work fine. The WeakPtr can be assigned to from the
SmartPtr. But the caller shouldn't have to do that.
Or am I wrong in assuming I shouldn't be putting raw pointers into weak
pointers? WeakPtr::getPtr() would return NULL since there'd never be a
strong ref to the ptr.
This seems like a ridiculous thing to be stumbling on, but I'm not sure
what to do. Thanks for any help.
-jim