Robert Osfield schrieb:
Hi Andreas,
On 11/5/06, Andreas Goebel <[EMAIL PROTECTED]> wrote:
osg::Geode* myStupidFunction(){
...
osg::ref_ptr<osg::Geode> x = new osg::geode();
return x.get();
}
This is will lead to a x ref_ptr<> deleting the goede, and dangling
pointer being passed back. It is certainly an unsafe thing to do.
Only returning a ref_ptr<> would be the safe when using .get().
Don's docs on ref_ptr example this scoping aspect to ref counting.
The right way to manage the ref counting such that the object doesn't
get deleted is to do:
osg::Geode* myStupidFunction(){
...
osg::ref_ptr<osg::Geode> x = new osg::geode();
return x.release(); // decrement the ref count but do no delete
even if ref count goes to 0.
}
Have a search through the OSG for instances of release to see it in
action.
or would it even be safe to use a naked pointer in the calling function?
i.e.:
osg::Geode* myStupidFunction(){
...
osg::Geode* x = new osg::geode();
return x;
}
This is pretty safe. An exception could cause a memory leak, and
potential the function might not be managed correctly, but if you
program correctly this isn't an issue, and a memory leak rarely kills
anyone, especially one that the app is likely to die due anyway.
If want to be really really really safe then use ref_ptr<> everywhere.
Personally I find this type of programming way over the top, not
seeing the wood from the tree type problem. Its important to
understand ref counting to be able to write robust C++ apps, and its
important to understand the performance implications too so using them
everywhere could be a killer.
Robert.
Thank you, that was a very good explanation!
Andreas
_______________________________________________
osg-users mailing list
[email protected]
http://openscenegraph.net/mailman/listinfo/osg-users
http://www.openscenegraph.org/