From KitwarePublic
< VTK‎ | Tutorials
Revision as of 16:31, 24 October 2009 by Daviddoria (talk | contribs)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

One way to create a VTK object is

vtkObject* MyObject = vtkObject::New();

This method, however, can (and likely will) lead to memory management issues at some point or another. You must manually delete the object


or you will have a memory leak. VTK's solution to this ever-annoying problem is the smart pointer. To use it, you must

#include "vtkSmartPointer.h"

Then you can create an object as follows:

vtkSmartPointer<vtkObject> MyObject = vtkSmartPointer<vtkObject>::New();

The idea behind smart pointers is reference counting. If the object goes out of scope and it is not being used anywhere else, it will be deleted automatically. Pretty 'smart', eh?!

When not allocating memory for an object, you can still use smart pointers. Take this simple example:

vtkSmartPointer<vtkXMLPolyDataReader> Reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();
vtkPolyData* pd = Reader->GetOutput();


vtkSmartPointer<vtkPolyData> pd = Reader->GetOutput();

In the first case, when the reader object goes out of scope, the data is deleted. In the second case, by using a smart pointer we have incremented the data's reference count by 1, so the data will not be deleted until the reader AND the polydata object go out of scope.

Here is an example of equivalent operations with and without smart pointers:


#include <vtkFloatArray.h>
#include <vtkSmartPointer.h>

#include <iostream>

void WithSmartPointers();
void WithoutSmartPointers();

int main(int argc, char *argv[])
	return 0;

void WithSmartPointers()
  vtkSmartPointer<vtkFloatArray> Distances = vtkSmartPointer<vtkFloatArray>::New();

void WithoutSmartPointers()
  vtkFloatArray* Distances = vtkFloatArray::New();


cmake_minimum_required(VERSION 2.6)



ADD_EXECUTABLE(SmartPointers SmartPointers.cpp)

TARGET_LINK_LIBRARIES(SmartPointers vtkHybrid)