Medical Imaging Interaction Toolkit  2026.06.00
Medical Imaging Interaction Toolkit
mitkReferenceCountWatcher.h
Go to the documentation of this file.
1 /*============================================================================
2 
3 The Medical Imaging Interaction Toolkit (MITK)
4 
5 Copyright (c) German Cancer Research Center (DKFZ)
6 All rights reserved.
7 
8 Use of this source code is governed by a 3-clause BSD license that can be
9 found in the LICENSE file.
10 
11 ============================================================================*/
12 
13 #ifndef mitkReferenceCountWatcher_h
14 #define mitkReferenceCountWatcher_h
15 
16 #include <itkCommand.h>
17 #include <MitkCoreExports.h>
18 #include <mitkCommon.h>
19 
20 namespace mitk
21 {
29  class ReferenceCountWatcher : public itk::Object
30  {
31  public:
32  typedef itk::SimpleMemberCommand<ReferenceCountWatcher> CommandType;
33 
35 
36  protected:
38  itk::Object *m_Object;
39 
41  std::string m_Comment;
42 
44  bool m_Deleted;
45 
47  CommandType::Pointer m_DeleteCommand;
48 
49  public:
55  ReferenceCountWatcher(itk::Object *o, const char *comment = "")
56  : m_Object(o), m_Comment(comment), m_Deleted(false), m_ObserverTag(0)
57  {
58  m_DeleteCommand = CommandType::New();
59  m_DeleteCommand->SetCallbackFunction(this, &ReferenceCountWatcher::DeleteObserver);
60  if (m_Object != nullptr)
61  m_ObserverTag = m_Object->AddObserver(itk::DeleteEvent(), m_DeleteCommand);
62  m_ReferenceCount = 0;
63  }
64 
67  {
68  if ((m_Deleted == false) && (m_Object != nullptr))
69  {
70  m_Object->RemoveObserver(m_ObserverTag);
71  }
72  }
73 
79  int GetReferenceCount() const override
80  {
81  if (m_Object == nullptr)
82  return -1;
83  if (m_Deleted)
84  return 0;
85  return m_Object->GetReferenceCount();
86  }
87 
89  itkGetStringMacro(Comment);
90 
91  protected:
93  void DeleteObserver() { m_Deleted = true; }
94  unsigned long m_ObserverTag;
95  };
96 }
97 
98 #endif
Keeps track of the reference count of an object even if it is destroyed.
~ReferenceCountWatcher() override
Destructor. Removes the observer from the watched object if it still exists.
bool m_Deleted
If true, m_Object is no longer valid and the returned reference count will be 0.
void DeleteObserver()
Callback invoked on itk::DeleteEvent() of the watched object.
ReferenceCountWatcher(itk::Object *o, const char *comment="")
Constructor requiring the object to be watched and allowing an optional comment.
itk::Object * m_Object
The object to be watched.
mitkClassMacroItkParent(ReferenceCountWatcher, itk::Object)
itk::SimpleMemberCommand< ReferenceCountWatcher > CommandType
int GetReferenceCount() const override
Returns the reference count of the watched object.
std::string m_Comment
Optional comment, e.g. for debugging output.
unsigned long m_ObserverTag
ITK observer tag for the delete event.
CommandType::Pointer m_DeleteCommand
itk::Command to get a notification when the object is deleted.
Find image slices visible on a given plane.