VTK

From bone.wiki
Jump to navigation Jump to search

Tips

Generic C++ Tips

Please familiarize yourself with C++ Development. Tips there apply to VTK classes too, which are after all C++ classes.

Minimize includes in headers

The general rule of header files in VTK is that you include only the header file of the superclass. For everything else, you merely forward declare it in the header. See C++ Development#Minimize includes in headers for more info on forward declarations.

This is a good rule to follow where possible in C++ anyways, but in VTK it is particularly important, because many kinds of objects (e.g. STL - Standard Template objects) will cause Python Wrapping of the class to fail if used in the header file.

Use vtkSmartPointers

VTK requires you to create instances of VTK objects only with the classes static New method, like this:

vtkImageData* image = vtkImageData::New();

The reason for this is that VTK uses reference counting internally, and will automatically delete objects that are no longer used. This is very convenient, because you can create an object somewhere, and link it into one or more pipeline, and not have worry about exactly when to delete it. It has however the disadvantage that when objects are created this way, they will not be automatically destroyed when they go out of scope. This is it should be - we only want them destroyed when their reference count goes to zero. However, you must remember to manually call Delete when the object goes out of scope, like this:

image->Delete();

This may not actually delete the object, it merely decrements the reference counter. It's easy to forget this (or to overlook paths that can take you out of scope - for instance if an exception is thrown.) If you forget, this becomes a memory leak. The best solution to this is to use a vtkSmartPointer, like this:

vtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New();

This is the only line of code you have to change compared to the abover example - otherwise you can use the variable image exactly as before. Only now, as soon as image goes out of scope, the destructor of the SmartPointer will be called, and it will automatically call the Delete method of image.

Use Doxygen style comments

to write