[vtkusers] Recreating a smart pointer object after deletion

David Gobbi david.gobbi at gmail.com
Tue Nov 23 12:41:12 EST 2010


On Tue, Nov 23, 2010 at 10:35 AM, David Gobbi <david.gobbi at gmail.com> wrote:

> On Tue, Nov 23, 2010 at 10:04 AM, David Doria <daviddoria at gmail.com>wrote:
>
>> Once you Delete() a smart pointer, how do you create a new object with
>> the same pointer?
>>
>> Below is a demo. Can someone please confirm or correct the comments?
>>
>> // Create a smart pointer to a vtkFloatArray object
>>  vtkSmartPointer<vtkFloatArray> distances =
>>    vtkSmartPointer<vtkFloatArray>::New();
>>  std::cout << distances->GetNumberOfComponents() << std::endl;
>>
>> // Delete the vtkFloatArray object, but the smart pointer still exists
>>  distances->Delete();
>>  //std::cout << distances->GetNumberOfComponents() << std::endl; //
>> Of course this will crash
>>
>
> Yeah, calling Delete() on a smart pointer is not a good thing.
>
>
>> // This is wrong, because this creates another smart pointer AND another
>> object
>>  distances = vtkSmartPointer<vtkFloatArray>::New();
>>  std::cout << distances->GetNumberOfComponents() << std::endl; //
>> Even though it is wrong, it seems like it should still work, but it
>> crashes
>>
>
> Like you, my first guess is that it should work. But I suspect that it
> breaks because it doesn't do reference count additions/subtractions in the
> correct order, what with the creation of a temporary smart pointer followed
> by assignment to another smart pointer and deletion of the temporary.
>
>
>> // This is right because it leaves the smart pointer alone and gives
>> it a new vtkFloatArray object
>>  distances.Take(vtkFloatArray::New());
>>  std::cout << distances->GetNumberOfComponents() << std::endl; // It
>> still crashes (Deleting unknown object: vtkObjectBase)
>>
>
> The method you want is TakeReference().  The Take() method is a static
> method.
>
>   David
>

Just another quick comment: after calling Delete() on a smart pointer, any
use of that smart pointer (including reassigning it) will cause a crash.  I
suspect even your second code block with vtkSmartPointer::New() will work if
you remove the Delete().

When you reassign a smart pointer, its previous contents are automatically
freed.

  David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.vtk.org/pipermail/vtkusers/attachments/20101123/d8e10707/attachment.htm>


More information about the vtkusers mailing list