[vtkusers] Returning a smart pointer
Jeff Baumes
jeff.baumes at kitware.com
Fri Nov 6 09:07:48 EST 2009
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.vtk.org/pipermail/vtkusers/attachments/20091106/875d32fd/attachment.htm>
More information about the vtkusers
mailing list