From 6f2647884e2d74d8853cfc83adcff2d73a052b9a Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Tue, 28 Jul 2026 15:16:30 -0400 Subject: [PATCH] fix: do not create map cells when adding or subtracting zero map_impl::reference::operator+= and operator-= emplaced a cell for a missing index even when the result stayed at value_type{}. Compute the result in a temporary and emplace only if it is non-default, as operator/= already does. Assisted-by: ClaudeCode:claude-opus-5 --- include/boost/histogram/storage_adaptor.hpp | 10 ++++++---- test/storage_adaptor_test.cpp | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/include/boost/histogram/storage_adaptor.hpp b/include/boost/histogram/storage_adaptor.hpp index 40383cb4..563bdeda 100644 --- a/include/boost/histogram/storage_adaptor.hpp +++ b/include/boost/histogram/storage_adaptor.hpp @@ -171,8 +171,9 @@ struct map_impl : T { if (it != static_cast(map)->end()) { it->second += u; } else { - auto pair = map->emplace(idx, value_type{}); - pair.first->second += u; + value_type tmp{}; + tmp += u; + if (!(tmp == value_type{})) map->emplace(idx, tmp); } return *this; } @@ -184,8 +185,9 @@ struct map_impl : T { if (it != static_cast(map)->end()) { it->second -= u; } else { - auto pair = map->emplace(idx, value_type{}); - pair.first->second -= u; + value_type tmp{}; + tmp -= u; + if (!(tmp == value_type{})) map->emplace(idx, tmp); } return *this; } diff --git a/test/storage_adaptor_test.cpp b/test/storage_adaptor_test.cpp index 88ac2b8f..a2533bc3 100644 --- a/test/storage_adaptor_test.cpp +++ b/test/storage_adaptor_test.cpp @@ -211,6 +211,23 @@ int main() { BOOST_TEST(std::isnan(static_cast(a[1]))); } + // adding or subtracting zero must not create cells in map-based storage_adaptor + { + using map_t = std::map; + auto a = storage_adaptor(); + a.reset(4); + a[0] += 0; + a[1] -= 0; + BOOST_TEST_EQ(static_cast(a).size(), 0); + BOOST_TEST_EQ(a[0], 0); + BOOST_TEST_EQ(a[1], 0); + a[2] += 1; + a[3] -= 1; + BOOST_TEST_EQ(static_cast(a).size(), 2); + BOOST_TEST_EQ(a[2], 1); + BOOST_TEST_EQ(a[3], -1); + } + // with accumulators::weighted_sum { auto a = storage_adaptor>>();