Skip to content

Commit

Permalink
STYLE: Avoid optimization initializedGlobalSingletonIndex by volatile
Browse files Browse the repository at this point in the history
Passing `initializedGlobalSingletonIndex` to a dummy function (`Unused`) may not
always avoid being optimized out. Instead, the C++ `volatile` keyword is really
meant to be used to avoid such optimization.

Added the C++17 `[[maybe_unused]]` attribute to avoid possible warnings.
  • Loading branch information
N-Dekker committed Aug 20, 2023
1 parent c3ae515 commit 48b7287
Showing 1 changed file with 2 additions and 8 deletions.
10 changes: 2 additions & 8 deletions Modules/Core/Common/src/itkSingleton.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ std::once_flag globalSingletonOnceFlag;
// has been loaded. In some cases, this call will perform the initialization.
// In other cases, static initializers like the IO factory initialization code
// will have done the initialization.
itk::SingletonIndex * initializedGlobalSingletonIndex = itk::SingletonIndex::GetInstance();
[[maybe_unused]] itk::SingletonIndex * volatile initializedGlobalSingletonIndex = itk::SingletonIndex::GetInstance();

/** \class GlobalSingletonIndexInitializer
*
Expand All @@ -53,13 +53,7 @@ class GlobalSingletonIndexInitializer
static SingletonIndex *
GetGlobalSingletonIndex()
{
std::call_once(globalSingletonOnceFlag, []() {
m_GlobalSingletonIndex = new SingletonIndex;

// To avoid being optimized out. The compiler does not like this
// statement at a higher scope.
Unused(initializedGlobalSingletonIndex);
});
std::call_once(globalSingletonOnceFlag, []() { m_GlobalSingletonIndex = new SingletonIndex; });

return m_GlobalSingletonIndex;
}
Expand Down

0 comments on commit 48b7287

Please sign in to comment.