[vtkusers] SmartPointer questions

Jeff Baumes jeff.baumes at kitware.com
Fri Oct 23 10:51:07 EDT 2009


On Thu, Oct 22, 2009 at 3:57 PM, David Doria
<daviddoria+vtk at gmail.com<daviddoria%2Bvtk at gmail.com>
> wrote:

> 1) Smart pointers when not allocating memory (using New())
> Given the below context, does it make sense to make polydata a smart
> pointer? Or is the actual memory released when the reader goes out of
> scope so a normal polydata pointer is the "right" thing to do?
>
> vtkSmartPointer<vtkXMLPolyDataReader> reader =
> vtkSmartPointer<vtkXMLPolyDataReader>::New();
> reader->SetFileName(InputFilename.c_str());
> reader->Update();
>
> //the question is which of these to use?
> vtkPolyData* polydata = reader->GetOutput(); //normal pointer
> vtkSmartPointer<vtkPolyData> polydata = reader->GetOutput(); //smart
> pointer
>

Contrary to what Dominik said, the polydata will not get deleted in the
second case until both the reader is deleted AND the polydata variable is
out of scope. The operation vtkSmartPointer<T> v = obj will increase obj's
reference count by 1 (the smart pointer will own that object's reference
count).

As a general fact, you can always keep objects around by calling
obj->Register(0), which simply increases the reference count by 1. Deep
copies aren't normally required.


>
> 2) What happens if you accidentally do this:
> vtkSmartPointer<vtkXMLPolyData> polydata = vtkPolyData::New();
> (vtkSmartPointer<> is missing on the rvalue)
>
> It seems to behave just like as if you had not used a smart pointer at
> all - the object does not get automatically deleted when it goes out
> of scope. So this is just assigning a normal pointer to a smart
> pointer variable? Can that be caught to produce a warning/error? Or is
> there any case in which you would want to do something like this? Is
> this exactly the same thing that is going on in the first question?
>

This behavior is due to the fact above. The reference count will be 2 after
that link (1 from New(), 1 in the smart pointer), so it will only go down to
1 when the variable is out of scope.

Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.vtk.org/pipermail/vtkusers/attachments/20091023/be9cab53/attachment.htm>


More information about the vtkusers mailing list