diff --git a/Modules/Core/Metadata/src/otbImageMetadata.cxx b/Modules/Core/Metadata/src/otbImageMetadata.cxx
index 21a24a6afdc61dc3d094774dfc54ff210c7f9a93..1d07f4c7b4073c968e9792538f503d7a8c20832e 100644
--- a/Modules/Core/Metadata/src/otbImageMetadata.cxx
+++ b/Modules/Core/Metadata/src/otbImageMetadata.cxx
@@ -477,7 +477,8 @@ void ImageMetadata::compact()
   bool compactVal;
   // TODO Compact the GeometryKeys when comparisons exists
   // Compact NumericKeys
-  for (const auto& kv : this->Bands.front().NumericKeys)
+  auto numKeys = this->Bands.front().NumericKeys;
+  for (const auto& kv : numKeys)
   {
     compactVal = true;
     auto bandIt = this->Bands.cbegin();
@@ -502,7 +503,8 @@ void ImageMetadata::compact()
     }
   }
   // Compact StringKeys
-  for (const auto& kv : this->Bands.front().StringKeys)
+  auto strKeys = this->Bands.front().StringKeys;
+  for (const auto& kv : strKeys)
   {
     compactVal = true;
     auto bandIt = this->Bands.cbegin();
@@ -529,7 +531,8 @@ void ImageMetadata::compact()
   // TODO Compact LUT1DKeys when comparisons exists
   // TODO Compact LUT2DKeys when comparisons exists
   // Compact TimeKeys
-  for (const auto& kv : this->Bands.front().TimeKeys)
+  auto timeKeys = this->Bands.front().TimeKeys;
+  for (const auto& kv : timeKeys)
   {
     compactVal = true;
     auto bandIt = this->Bands.cbegin();
@@ -554,7 +557,8 @@ void ImageMetadata::compact()
     }
   }
   // Compact ExtraKeys
-  for (const auto& kv : this->Bands.front().ExtraKeys)
+  auto extraKeys = this->Bands.front().ExtraKeys;
+  for (const auto& kv : extraKeys)
   {
     compactVal = true;
     auto bandIt = this->Bands.cbegin();