VTKのvtkSmartPointerは参照カウンタ付きだが、vtkWeakPointerもある(初めて知った)。
まず以下は、vtkSmartPointerを使った場合で、ポインタをコピーするたびに参照カウンタが増え、ポインタにnullptrを代入して無効化することで参照カウンタが減ることを確認する。
vtkSmartPointer<vtkActor> actor1 = vtkSmartPointer<vtkActor>::New(); std::cout << "actor1 reference count: " << actor1->GetReferenceCount() << std::endl; vtkSmartPointer<vtkActor> actor2 = actor1; std::cout << "actor2 reference count: " << actor2->GetReferenceCount() << std::endl; actor1 = nullptr;// actor1を無効化 std::cout << "Delete" << std::endl; // ここは通らない if(actor1) std::cout << "actor1 reference count: " << actor1->GetReferenceCount() << std::endl; if(actor2) std::cout << "actor2 reference count: " << actor2->GetReferenceCount() << std::endl;
vtkWeakPointer<vtkActor> weak_actor; // WeakPointerを定義
{ vtkSmartPointer<vtkActor> actor1 = vtkSmartPointer<vtkActor>::New(); std::cout << "actor1 reference count: " << actor1->GetReferenceCount() << std::endl; weak_actor = actor1;// actor1 を弱参照 参照カウンタは増えない std::cout << "weak_actor reference count: " << weak_actor->GetReferenceCount() << std::endl; vtkSmartPointer<vtkActor> actor2 = actor1; std::cout << "actor2 reference count: " << actor2->GetReferenceCount() << std::endl; actor1 = nullptr; std::cout << "Delete" << std::endl; // ここは通らない if (actor1) std::cout << "actor1 reference count: " << actor1->GetReferenceCount() << std::endl; if (actor2) std::cout << "actor2 reference count: " << actor2->GetReferenceCount() << std::endl; }
if (weak_actor) { // ここは通らない std::cout << "actor1 reference count: " << weak_actor->GetReferenceCount() << std::endl; } else { // こちらを通る std::cout << "actor is deleted" << std::endl; }