Hi Kevin,

My project is throwing an occasional "unhandled win32 exception" error and I've been trying to figure out why. There is no consistency in the timing so I assume that I have a dangling pointer somewhere.

I doubt you're on the right track with changing standard pointers to ref_ptrs in function arguments, but when unsure it's better to use ref_ptrs everywhere.

The "right way" to debug your error would be to compile a debug version and run your code in a debugger. Then the debugger would likely tell you exactly which pointer was left dangling, you'd have a stack trace, and it would be relatively easy to track down the cause. Just sprinkling ref_ptrs everywhere in the hope that it'll fix it is not a solution, IMHO.

But to answer your more concrete question:

Is there an equivalant means of casting an osg::ref_ptr<osg::node> into an 
osg::ref_ptr<osg::MatrixTransform> when using referenced object pointers? I'm trying 
to do something like:

--- snip ---

void operator()( osg::ref_ptr<osg::Node> node, osg::ref_ptr<osg::NodeVisitor> 
nv )
{
  osg::ref_ptr<osg::MatrixTransform> MatrixXform = 
dynamic_cast<osg::ref_ptr<osg::MatrixTransform>(node) ;

if ( MatrixXform )

--- snip ---

osg::ref_ptr<osg::MatrixTransform> MatrixXform =
    dynamic_cast<osg::MatrixTransform*>(node.get());

A ref_ptr is an object on the stack (not a pointer) that tracks a pointer. And ref_ptr::get() returns a raw pointer to the underlying object. So you can construct (or here, assign to) a ref_ptr from a raw pointer.

So from right to left:
1. You extract the raw Node* pointer from a ref_ptr<Node>
2. You dynamic_cast that to a MatrixTransform*
3. You assign that to a ref_ptr<MatrixTransform>
4. Bob is your uncle.

Note that in the process, the ref count of node will be incremented if it was really a MatrixTransform (i.e. if the assignment assigned something other than NULL), so your function will have 2 refs (one in the temporary ref_ptr<Node>, and one in the ref_ptr<MatrixTransform>). This is unnecessary, as the temporary ref_ptr<Node> in the function arguments guarantees that the object will not be deleted in the scope of the function. So you could do this instead:

osg::MatrixTransform* MatrixXform =
    dynamic_cast<osg::MatrixTransform*>(node.get());

As I said, storing it in a raw pointer is safe at that point because of the temporary ref_ptr<Node> in the function arguments which will be destroyed when the function ends.

So you see, ref_ptrs require a bit of work wrapping your mind around them, but it's not magic and it all works really well.

Hope this helps,

J-S
--
______________________________________________________
Jean-Sebastien Guay    [email protected]
                               http://www.cm-labs.com/
                        http://whitestar02.webhop.org/
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to