[vtkusers] Initializing smart pointers (was: Update vtkDelaunay2d object)

Kenneth Porter shiva at sewingwitch.com
Tue Feb 23 07:20:33 EST 2010


--On Monday, February 22, 2010 11:11 PM -0600 Jordi Gutiérrez Hermoso 
<jordigh at gmail.com> wrote:

> Interesting. Why? I was just treating vtkSmartPointer like
> boost::shared_ptr, but I guess its API is not analogous.

Boost (and the upcoming standard extension) implement the shared pointer's 
reference count as part of the pointer. VTK implements the reference count 
as part of the vtkObject base class. vtkSmartPointer simply registers its 
own reference in the object it points to.

If you create an object with vtkSomeClass::New(), you initialize its 
internal reference count to 1. If you then assign this to a 
vtkSmartPointer, its count is now 2. When the vtkSmartPointer goes out of 
scope, the count is still 1, so the object is not automatically 
garbage-collected.

vtkSmartPointer declares its own special convenience New() method which 
creates an object with an initial reference count of zero, so that it can 
be used to initialize the smart pointer.

If you already have the bare pointer by other means and want to give the 
smart pointer its self-ownership, use the Take() method:

   vtkMyClass* bareClassPointer = vtkMyClass::New();
   vtkSmartPointer<vtkMyClass> myClass;
   myClass.Take(bareMyClassPointer);

As a rule, Take() is only needed when interfacing to code that doesn't use 
smart pointers.



More information about the vtkusers mailing list