From 5a74cb42ff21cc2ae6ab82ed278db5751fd7264b Mon Sep 17 00:00:00 2001 From: greg Date: Sun, 16 Aug 2020 18:44:12 -0400 Subject: [PATCH] update try_emplace_l so that the lambda is called only when the key was already present - issue #60 --- parallel_hashmap/phmap.h | 6 ++++-- tests/parallel_hash_map_test.cc | 10 +++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/parallel_hashmap/phmap.h b/parallel_hashmap/phmap.h index b6a856d..9de4930 100644 --- a/parallel_hashmap/phmap.h +++ b/parallel_hashmap/phmap.h @@ -3457,8 +3457,10 @@ public: inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct, std::forward_as_tuple(std::forward(k)), std::forward_as_tuple(std::forward(args)...)); - auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))); - std::forward(f)(Policy::value(&*it)); + else { + auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))); + std::forward(f)(Policy::value(&*it)); + } return std::get<2>(res); } diff --git a/tests/parallel_hash_map_test.cc b/tests/parallel_hash_map_test.cc index 5810b19..793622c 100644 --- a/tests/parallel_hash_map_test.cc +++ b/tests/parallel_hash_map_test.cc @@ -32,13 +32,13 @@ TEST(THIS_TEST_NAME, ThreadSafeContains) { m.try_emplace_l(2, [](int& v) { v = 5; }); EXPECT_EQ(m[2], 5); - // insert a valye that is not already present - m.try_emplace_l(3, [](int& v) { assert(v == 0); v = 6; }); - EXPECT_EQ(m[3], 6); + // insert a valye that is not already present. Will be default initialised to 0 and lambda not called + m.try_emplace_l(3, [](int& v) { assert(v == 0); /* should not be called when value constructed */ v = 6; }); + EXPECT_EQ(m[3], 0); // insert a valye that is not already present, provide argument to value-construct it - m.try_emplace_l(4, [](int& v) { assert(v == 999); v = 5; }, 999); - EXPECT_EQ(m[4], 5); + m.try_emplace_l(4, [](int& ) { assert(0); /* should not be called when value constructed */ }, 999); + EXPECT_EQ(m[4], 999); }