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 allocate and free vtlib objects with the C++ operators new and delete.  This is because there are many possible interactions between objects, such as nodes in the scene graph referencing each other.  In order to safely destroy objects, there is one simple step:

Don't use delete to destroy an object.  Instead call its Release() method when you are done with it:

vtGroup *pGroup = new vtGroup;
pGroup->Release();

What's going on

Behind the scenes, there is a reference count for each vtlib object.  This count starts out with the value 1.  Each additional reference to the object increases the count, each dereference (such as calling Release()) decreases the count.  When the count reaches 0, the object deletes itself.

Ownership

When one object references another, it can be said to "own" the object.  For example:

If an object does not need to persist after it is no longer referenced, you can (and should) release it after you have passed ownership.  For example:

vtMaterialArray *mats = new vtMaterialArray();
mats->Append(new vtMaterial(...));
vtGeom *geom = new vtGeom();
geom->SetMaterials(mats);
mats->Release();

In this example, ownership of the material array is pass to the geometry.  The material array will be automatically deleted when the geometry is deleted (or it decides to use another another material array).