Using vtlib Objects

Here is an explanation of how to create and destroy vtlib objects in a robust fashion, without memory leaks.

The Need for Abstraction

Unlike many other libraries, you cannot simply free vtlib objects with the C++ operator delete.  This is because there are many possible interactions between objects, such as nodes in the scene graph referencing each other.  In order to handle objects safely, OSG provides a reference counting mechanism.  Fortunately, most vtlib objects are subclassed from OSG's osg::referenced.

Don't use delete to destroy an object.  Instead keep a ref_ptr to the object, which will automatically  method when you are done with it:

osg::ref_ptr<vtGroup> pGroup = new vtGroup;

There are typedefs provides for most classes, so you can state it even more simply:

vtGroupPtr pGroup = new vtGroup;

What's going on

Behind the scenes, there is a reference count for each vtlib object.  This count starts out with the value 1 because of the refpointer you used when you allocated it.  Each additional reference to the object increases the count, each dereference decreases the count.  When the count reaches 0, the object deletes itself.