2
votes

I am using VTK for Visualization and my code is full of their smartpointers, like:

vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();

what I was wondering about if this New() should not be followed later by Delete(). Or does VTK destroy everything "automatically". Many times by using Delete() my code crashes. So, I was wondering if I should use it in first place and what is behind New(), a shared pointer or something like this?

2

2 Answers

9
votes

vtkSmartPointer will destroy the object "automatically" when out of scope. The Delete() method is called in the dtor of it.

Without vtkSmartPointer, you need to take care the memory management issues by yourself and call Delete(), like following

vtkObject* MyObject = vtkObject::New();
MyObject->Delete();

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

See the wiki page: http://www.vtk.org/Wiki/VTK/Tutorials/SmartPointers

6
votes

Another alternative to

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

is

vtkNew<vtkObject> MyObject;

Just note that when passing MyObject to functions/methods that take in a vtkObject*, you have to use MyObject.GetPointer() e.g.

foo->SetObject(MyObject.GetPointer());