VTK: Difference between revisions
| Line 3: | Line 3: | ||
===Generic C++ Tips=== | ===Generic C++ Tips=== | ||
Please familiarize yourself with [[C++ Development]]. | Please familiarize yourself with [[C++ Development]]. Tips there apply to VTK classes too, which are after all C++ classes. | ||
===Use vtkSmartPointers=== | ===Use vtkSmartPointers=== | ||
Revision as of 23:17, 7 December 2009
Tips
Generic C++ Tips
Please familiarize yourself with C++ Development. Tips there apply to VTK classes too, which are after all C++ classes.
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