[osg-users] ref_ptr, ptr and leaking question (quite simple)

Maciej Krol mackrol at gmail.com
Sat Jul 26 03:03:09 PDT 2008

Hi Sam,

Constructor of osg::Geode does not increment ref count, since objects can be
allocated either on heap or stack.
The osg::ref_ptr manages ref count of object. Ref count is incremented in
constructor or assignment operator of ref_ptr and decremented in its

osg::Geode *g = new osg::Geode; // refCount = 0, object constructor does not
increment refCount
viewer.setSceneData(g) // refCount = 1, scene data is a osg::ref_ptr

Object ref count is managed starting from first osg::ref_ptr assignment.
Your code is OK until You are sure that the osg::Geode *g will be assigned
to osg::ref_ptr. Better solution is to manage Your objects as soon as

osg::ref_ptr<osg::Geode> g = new osg::Geode; // refCount = 1
viewer.setSceneData(g.get()); // refCount = 2

Keep track of osg::ref_ptr scoping. For example in factory functions ref_ptr
can destroy object.

osg::Geode *createGeode(...)
    osg::ref_ptr<osg::Geode> g = new osg::Geode; // refCount = 1
    return g.get()
    // refCount = 0 g is destroyed

The solution is to avoid ref_ptr in this function or return ref_ptr instead.

osg::ref_ptr<osg::Geode> createGeode(...)
   osg::ref_ptr<osg::Geode> g = new osg::Geode; // refCount = 1
    return g;
    // refCount = 2 g is assigned to result ref_ptr
    // refCount = 1 g is destroyed

Maciej Krol

2008/7/26 Ariasgore <ariasgore at gmx.de>

> Hello,
> I have some novoice question about the use of pointers as short-time
> reference. As in the tutorial book described all objects deriving from
> osg::Referenced should be used with ref_ptr for proper use.
> But even in the book and in some tutorials there are many uses of the plain
> c++ pointer without the reference use of ref_ptr.
> There is where I have one question, if I develop in VisualStudio for
> instance and write some code like:
> osg::Geode * g = new osg::Geode;
> ...
> viewer.setSceneData(g);
> Doesn't I have a ref count of 2 for g? Whild would result in a leak since I
> never delete the g pointer manually?
> If this above is true and the programm is running as a childprocess of my
> IDE (since I have debugging and stacktracing and so on), don't I create some
> leaking beyond the lifetime of the programm? I am not quite sure if the
> memory is cleaned after finishing the programm or the whole IDE.
> Thanks
> Sam
> _______________________________________________
> osg-users mailing list
> osg-users at lists.openscenegraph.org
> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openscenegraph.org/pipermail/osg-users-openscenegraph.org/attachments/20080726/e6d3b73d/attachment-0003.htm>

More information about the osg-users mailing list