From 937c3484cf32704f7c7fd69cbff45165b9d65aa0 Mon Sep 17 00:00:00 2001 From: LeonineKing1199 Date: Mon, 22 Nov 2021 12:27:29 -0800 Subject: [PATCH] Flesh out test case --- test/unordered/transparent_tests.cpp | 97 ++++++++++++++++++---------- 1 file changed, 64 insertions(+), 33 deletions(-) diff --git a/test/unordered/transparent_tests.cpp b/test/unordered/transparent_tests.cpp index 22c20905..b5cc5bfc 100644 --- a/test/unordered/transparent_tests.cpp +++ b/test/unordered/transparent_tests.cpp @@ -13,52 +13,83 @@ #include -struct key { - int x_; - static int count_; +struct key +{ + int x_; + static int count_; - explicit key(int x) : x_(x) { - ++count_; - } + key(int x) : x_(x) { ++count_; } + key(key const& k) : x_(k.x_) { ++count_; } + + key& operator=(key const& k) + { + x_ = k.x_; + ++count_; + return *this; + } }; int key::count_; -UNORDERED_AUTO_TEST(transparent_count) { - key::count_ = 0; +struct transparent_hasher +{ + typedef void is_transparent; - struct hasher { - std::size_t operator()(key const& k) const { - return boost::hash()(k.x_); - } + std::size_t operator()(key const& k) const + { + return boost::hash()(k.x_); + } - std::size_t operator()(int const k) const { - return boost::hash()(k); - } - }; + std::size_t operator()(int const k) const { return boost::hash()(k); } +}; - struct key_equal { - bool operator()(key const& k1, key const& k2) const { - return k1.x_ == k2.x_; - } +struct transparent_key_equal +{ + typedef void is_transparent; - bool operator()(key const& k1, int const x) const { - return k1.x_ == x; - } + static bool was_called_; - bool operator()(int const x, key const& k1 ) const { - return k1.x_ == x; - } - }; + bool operator()(key const& k1, key const& k2) const { return k1.x_ == k2.x_; } + bool operator()(int const x, key const& k1) const + { + was_called_ = true; + return k1.x_ == x; + } +}; - boost::unordered_map map; - map.insert({key(0), 1337}); - BOOST_TEST(key::count_ == 1); +bool transparent_key_equal::was_called_; - std::size_t const count = map.count(0); +UNORDERED_AUTO_TEST (unordered_map_transparent_count) { + key::count_ = 0; + transparent_key_equal::was_called_ = false; - BOOST_TEST(count == 1); - BOOST_TEST(key::count_ == 1); + boost::unordered_map map; + + // initial `key(0)` expression increases the count + // then copying into the `unordered_map` increments the count again thus we + // have 2 + // + map[key(0)] = 1337; + BOOST_TEST(key::count_ == 2); + + // now the number of `key` objects created should be a constant and never + // touched again + // + std::size_t count = 0; + count = map.count(0); + + BOOST_TEST(count == 1); + BOOST_TEST(key::count_ == 2); + BOOST_TEST(map.key_eq().was_called_); + + count = map.count(1); + + BOOST_TEST(count == 0); + BOOST_TEST(key::count_ == 2); + + count = map.count(key(0)); + BOOST_TEST(count == 1); + BOOST_TEST(key::count_ > 2); } RUN_TESTS()