[vtkusers] About Pitfalls section in smart pointers tutorial

Marcus D. Hanwell marcus.hanwell at kitware.com
Thu Jun 30 11:33:06 EDT 2016


On Thu, Jun 30, 2016 at 3:02 AM, Elvis Stansvik
<elvis.stansvik at orexplore.com> wrote:
> 2016-06-29 21:42 GMT+02:00 Marcus D. Hanwell <marcus.hanwell at kitware.com>:
>>
>> On Wed, Jun 29, 2016 at 3:28 PM, Elvis Stansvik
>> <elvis.stansvik at orexplore.com> wrote:
>> > At
>> >
>> >    http://www.vtk.org/Wiki/VTK/Tutorials/SmartPointers#Pitfalls
>> >
>> > is this warning:
>> >
>> > "If you create an object and then change where it is pointing, the
>> > reference
>> > count will be incorrect. e.g.
>> >
>> > vtkSmartPointer<vtkPolyData> Polydata =
>> > vtkSmartPointer<vtkPolyData>::New();
>> > Polydata = Reader->GetOutput();
>> >
>> > In this case, memory is allocated for Polydata, but then we change
>> > Polydata
>> > to point to the output of Reader rather than the memory we just
>> > allocated.
>> > Instead, we should have done simply:
>> >
>> > vtkPolyData* Polydata = Reader->GetOutput();
>> >
>> > It was not necessary to use a smart pointer because we did not actually
>> > create any new objects"
>> >
>> > I fail to see how the refcount would be incorrect in the first approach.
>> > First a new object is created and its refcount increased to 1, then when
>> > Reader->GetOutput() (a raw pointer) is assigned to Polydata, wouldn't
>> > the
>> > smart pointer take care of decreasing the refcount for the object it
>> > already
>> > points to (so it would go to 0), before it starts managing the new
>> > pointer?
>> > Or is that not how it will work?
>> >
>> I have the same interpretation, it looks like it was added by David
>> Doria in 2009. It is silly to allocate a new object, and then
>> immediately point to something else without ever using that object,
>> but the reference count for that object should be correctly
>> decremented and so deleted as far as I can see.
>
>
> Yes, I forgot to say: I of course also think it's silly, I was just curious
> about the wording of that warning since it didn't make sense to me.
>
I removed the section from the wiki article, it would be better to
balance it with the other smart pointer types too possibly. All
vtkObject derived classes are implicitly reference counted for better
or worse, so the behavior is different to the STL smart pointers.

They interact with the objects reference count, I am a little biased
as I wrote it, but
https://blog.kitware.com/a-tour-of-vtk-pointer-classes/ (linked at the
top of that wiki page) provides a broad overview of the different
smart pointers and when/where they might be used.


More information about the vtkusers mailing list