Skip to content

Commit

Permalink
STYLE: Use volatile to avoid global SingletonIndex being optimized out
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.

Removed the claim that `Unused` ensures that its parameter is not optimized out.
  • Loading branch information
N-Dekker authored and hjmjohnson committed Oct 20, 2023
1 parent b9b9e14 commit a661e0e
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 10 deletions.
3 changes: 1 addition & 2 deletions Modules/Core/Common/include/itkSingleton.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@
*
* This function is to be used to mark parameters as unused to suppress
* compiler warning. It can be used when the parameter needs to be named
* (i.e. itkNotUsed cannot be used) but is not always used. It ensures
* that the parameter is not optimized out.
* (i.e. itkNotUsed cannot be used) but is not always used.
*/
template <typename T>
inline void
Expand Down
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 a661e0e

Please sign in to comment.