From f2783a9aa0157b50e272545edbcad9c3029195ff Mon Sep 17 00:00:00 2001 From: Niels Dekker Date: Wed, 28 Sep 2022 19:08:27 +0200 Subject: [PATCH] STYLE: Remove const_cast, make `Object::m_SubjectImplementation` mutable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- Modules/Core/Common/include/itkObject.h | 7 ++++++- Modules/Core/Common/src/itkObject.cxx | 10 +++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Modules/Core/Common/include/itkObject.h b/Modules/Core/Common/include/itkObject.h index 7b41692668d..9c7c699ca49 100644 --- a/Modules/Core/Common/include/itkObject.h +++ b/Modules/Core/Common/include/itkObject.h @@ -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 *); @@ -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 m_SubjectImplementation; + mutable std::unique_ptr m_SubjectImplementation; /** * Implementation for holding Object MetaData diff --git a/Modules/Core/Common/src/itkObject.cxx b/Modules/Core/Common/src/itkObject.cxx index cb2e8359998..3a63ffaa451 100644 --- a/Modules/Core/Common/src/itkObject.cxx +++ b/Modules/Core/Common/src/itkObject.cxx @@ -459,11 +459,8 @@ Object::GetGlobalWarningDisplay() unsigned long Object::AddObserver(const EventObject & event, Command * cmd) { - if (!this->m_SubjectImplementation) - { - this->m_SubjectImplementation = std::make_unique(); - } - return this->m_SubjectImplementation->AddObserver(event, cmd); + const auto & thisAsConst = *this; + return thisAsConst.AddObserver(event, cmd); } unsigned long @@ -471,8 +468,7 @@ Object::AddObserver(const EventObject & event, Command * cmd) const { if (!this->m_SubjectImplementation) { - auto * me = const_cast(this); - me->m_SubjectImplementation = std::make_unique(); + this->m_SubjectImplementation = std::make_unique(); } return this->m_SubjectImplementation->AddObserver(event, cmd); }