[vtkusers] Returning a smart pointer

Anja Ende anja.ende at googlemail.com
Fri Nov 6 10:42:25 EST 2009


Thanks Jeff. I will just create a class member.

2009/11/6 Jeff Baumes <jeff.baumes at kitware.com>:
>
>
> On Fri, Nov 6, 2009 at 6:26 AM, Anja Ende <anja.ende at googlemail.com> wrote:
>>
>> Hello,
>>
>> A quick question about returning a smart pointer from class functions.
>> Is this the correct ussage?
>>
>> class SomeClass
>> {
>>   vtkPolayData * SomeMethod()
>>   {
>>      vtkSmartPointer<vtkPolyData> myData =
>> vtkSmartPointer<vtkPolyData>::New();
>>      ....
>>      return myData;
>>   }
>> }
>>
>> In the caller:
>>
>> vtkPolyData * data = instance.SomeMethod();
>>
>> Would this work? Or am I better off with using class members and
>> deleting them in the destructor when I want to pass data around?
>>
>
> As written this would not work, the single reference would disappear after
> "return myData", since myData would go out of scope. You have a few options
> here:
> 1. Store it in a class member and call Delete() in the destructor as you
> suggest. This is the cleanest solution. If the caller desires to keep the
> poly data around after the lifetime of the SomeClass instance, it can just
> call data->Register(0) to own an additional reference.
> 2. Return the new instance without using smart pointers. This will leave a
> dangling reference, and the documentation should clearly state that whoever
> calls the method is responsible for calling Delete() on the resulting
> object. This is what is normally done for factory-type methods.
> Jeff



-- 
Cheers,

Anja



More information about the vtkusers mailing list