diff --git a/Common/Transforms/elxTransformIO.cxx b/Common/Transforms/elxTransformIO.cxx index b168287ea..8423eedba 100644 --- a/Common/Transforms/elxTransformIO.cxx +++ b/Common/Transforms/elxTransformIO.cxx @@ -171,15 +171,20 @@ elastix::TransformIO::ConvertItkTransformBaseToSingleItkTransform(const itk::Tra const auto instanceName = className + "_double_" + std::to_string(elxTransform.GetInputSpaceDimension()) + '_' + std::to_string(elxTransform.GetOutputSpaceDimension()) + optionalSplineOrderPostfix; - const auto instance = itk::ObjectFactoryBase::CreateInstance(instanceName.c_str()); - const auto itkTransform = dynamic_cast(instance.GetPointer()); - if (itkTransform == nullptr) + if (const auto instance = itk::ObjectFactoryBase::CreateInstance(instanceName.c_str())) { - return nullptr; + // itk::ObjectFactoryBase::CreateInstance appears to return an object that has ReferenceCount == 2. + assert(instance->GetReferenceCount() == 2); + instance->UnRegister(); + + if (const auto itkTransform = dynamic_cast(instance.GetPointer())) + { + itkTransform->SetFixedParameters(elxTransform.GetFixedParameters()); + itkTransform->SetParameters(elxTransform.GetParameters()); + return itkTransform; + } } - itkTransform->SetFixedParameters(elxTransform.GetFixedParameters()); - itkTransform->SetParameters(elxTransform.GetParameters()); - return itkTransform; + return nullptr; } diff --git a/Core/Main/GTesting/itkElastixRegistrationMethodGTest.cxx b/Core/Main/GTesting/itkElastixRegistrationMethodGTest.cxx index ae9c55566..c4f80ea42 100644 --- a/Core/Main/GTesting/itkElastixRegistrationMethodGTest.cxx +++ b/Core/Main/GTesting/itkElastixRegistrationMethodGTest.cxx @@ -1501,7 +1501,11 @@ GTEST_TEST(itkElastixRegistrationMethod, ConvertToItkTransform) for (unsigned int n{ 0 }; n < numberOfTransforms; ++n) { // TODO Check result - ElastixRegistrationMethodType::ConvertToItkTransform(*registration.GetNthTransform(n)); + const auto result = + ElastixRegistrationMethodType::ConvertToItkTransform(*registration.GetNthTransform(n)); + + ASSERT_NE(result, nullptr); + EXPECT_EQ(result->GetReferenceCount(), 1); } } }