Skip to content

Commit

Permalink
STYLE: Remove const_cast, make Object::m_SubjectImplementation mutable
Browse files Browse the repository at this point in the history
Removed the `const_cast` from the const overload of `Object::AddObserver`, and
removed duplicate code by having the non-const overload call the const overload.

Following C++ Core Guidelines, September 23, 2022, "Don’t cast away const", at
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es50-dont-cast-away-const

Added a note on why the non-const overload is still there.
  • Loading branch information
N-Dekker authored and dzenanz committed Oct 11, 2022
1 parent f8cd176 commit f2783a9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
7 changes: 6 additions & 1 deletion Modules/Core/Common/include/itkObject.h
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ class ITKCommon_EXPORT Object : public LightObject
* and an itk::Command to execute. It returns an unsigned long tag
* which can be used later to remove the event or retrieve the
* command.
*
* \note This member function is overloaded for const and non-const,
* just for backward compatibility. Removing the non-const overload
* appears to break the use of SWIG %pythonprepend in
* ITK/Wrapping/Generators/Python/PyBase/pyBase.i
*/
unsigned long
AddObserver(const EventObject & event, Command *);
Expand Down Expand Up @@ -275,7 +280,7 @@ class ITKCommon_EXPORT Object : public LightObject

/** Implementation class for Subject/Observer Pattern.
* This is only allocated if used. */
std::unique_ptr<SubjectImplementation> m_SubjectImplementation;
mutable std::unique_ptr<SubjectImplementation> m_SubjectImplementation;

/**
* Implementation for holding Object MetaData
Expand Down
10 changes: 3 additions & 7 deletions Modules/Core/Common/src/itkObject.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -459,20 +459,16 @@ Object::GetGlobalWarningDisplay()
unsigned long
Object::AddObserver(const EventObject & event, Command * cmd)
{
if (!this->m_SubjectImplementation)
{
this->m_SubjectImplementation = std::make_unique<SubjectImplementation>();
}
return this->m_SubjectImplementation->AddObserver(event, cmd);
const auto & thisAsConst = *this;
return thisAsConst.AddObserver(event, cmd);
}

unsigned long
Object::AddObserver(const EventObject & event, Command * cmd) const
{
if (!this->m_SubjectImplementation)
{
auto * me = const_cast<Self *>(this);
me->m_SubjectImplementation = std::make_unique<SubjectImplementation>();
this->m_SubjectImplementation = std::make_unique<SubjectImplementation>();
}
return this->m_SubjectImplementation->AddObserver(event, cmd);
}
Expand Down

0 comments on commit f2783a9

Please sign in to comment.