[vtkusers] vtkSmartPointer ReferenceCount Behavior

Henry Lehmann henry.lehmann at informatik.tu-freiberg.de
Tue Dec 11 03:07:31 EST 2012


Hello all,

i am using vtkSmartPointer and am encountering a strange problem.
to illustrate the problem i wrote following code.
please correct my comments, if they are wrong.

---
#include <vtkSphereSource.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkPassThrough.h>

#include <iostream>

int main(int argc, char* args[])
{
     using namespace std;

     vtkNew<vtkSphereSource> source;
     vtkNew<vtkXMLPolyDataWriter> sink;
     sink->SetFileName("abc.vtp");

     vtkSmartPointer<vtkPassThrough> pass_ptr;
     {
         // create new instance with refcount 1
         vtkNew<vtkPassThrough> pass;
         cout << pass->GetReferenceCount() << endl; // 1

         // increase refcount by assiging to smartptr
         pass_ptr = pass.GetPointer();
         cout << pass_ptr->GetReferenceCount() << endl;    // 2

     }
     // vtkNew instance goes out of scope and decreases refcounter
     cout << pass_ptr->GetReferenceCount() << endl; // 1

     // connect object to pipeline increases refcounter
     pass_ptr->SetInputConnection(source->GetOutputPort());
     cout << pass_ptr->GetReferenceCount() << endl; // 2

     // connect object to pipeline increases refcounter
     sink->SetInputConnection(pass_ptr->GetOutputPort());
     cout << pass_ptr->GetReferenceCount() << endl; // 2, why not 3?

     // disconnect object from pipeline decreases refcounter, but does 
not do it
     pass_ptr->RemoveAllInputConnections(0);
     cout << pass_ptr->GetReferenceCount() << endl; // 2

     // disconnect object from pipeline decreases refcounter, but does 
not do it
     sink->RemoveAllInputConnections(0);
     cout << pass_ptr->GetReferenceCount() << endl; // 2, why not 1?

     // is the object deleted with refcount 2?
     return 0;
}
---

i want to create a vtk object anywhere in my code and connect it to the 
pipeline.
if the object is not used anymore it shall be deleted.

i create new objects using vtkNew. afterwards they are added to a 
pipeline,  which
increases refcount and the vtkNew instance can go out of scope and the 
object is not deleted.

however, i do not get an example, which mimics this behavior since i do 
not understand the behavior of refcounting.

Best regards,
Henry




More information about the vtkusers mailing list