On Sat, Feb 6, 2010 at 4:07 AM, Kevin Wilder <[email protected]>wrote:

> Hi,
> ...
> I came upon a passage in the OpenSceneGraph Quick Start Guide that says:
>
> "Be careful when returning the address of an object from a function. If you
> do this incorrectly, the ref_ptr<> storing the memory address could go out
> of scope before the address is placed on the return stack."
>
> This is talking about the following anti-pattern:
osg::Node* func()
{
  osg::ref_ptr<Node> result;
...
  return result.get(); // result gets deleted!
}

Instead of returning "result.get()" you need to return "result.release()"
which prevents the ref_ptr destructor from deleting the object. As a side
node, I think this idiom is unfortunate; ref_ptrs should be returned by
loading and scene graph creation functions that run in the database pager
thread. Live objects with a ref count of 0 are a bad thing.


> I assume that this also applies when passing referenced objects to a
> function... But most of the examples of callback functions that I have seen
> on the web all use standard C++ pointers in the function definition, rather
> than ref_ptr<>. For example:
>
> --- snip ---
>
> void operator()( osg::Node* node, osg::NodeVisitor * nv )
> {
>  osg::MatrixTransform * MatrixXform =
> dynamic_cast<osg::MatrixTransform*>(node) ;
>
> if ( MatrixXform )
>
> This style of code is common in OSG. It is safe because the caller has a
ref_ptr somewhere that points to the node.

> --- snip ---
>
> Thinking that this may be the source of my dangling pointer, I tried to
> modify my own callback function definition to use referenced object pointers
> per the quick start guide's recommendations. Unfortunately, I got hung up on
> the dynamic_cast in the code above. I can't figure out how to cast the
> osg::node referenced object pointer into an osg::MatrixTransform referenced
> object pointer.
>
> 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 ---
>
> If you still want to do that, you can say
osg::ref_ptr<osg::MatrixTransform> MatrixXform =
dynamic_cast<osg::MatrixTransform*>(node.get());

>
> Thanks for the help. I'm relatively new to OpenSceneGraph programming.
>
> Cheers,
>
> Kevin
>
> Tim
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to