From c3896fa84d54e44dc1910d6f202a47d3640b6fa5 Mon Sep 17 00:00:00 2001 From: Juanli Shen Date: Thu, 25 Jul 2019 10:37:22 -0700 Subject: [PATCH] Make Map<> movable --- src/core/lib/gprpp/map.h | 17 +++++++++++++++++ test/core/gprpp/map_test.cc | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/core/lib/gprpp/map.h b/src/core/lib/gprpp/map.h index 36e32d60c07..2babe35cd1b 100644 --- a/src/core/lib/gprpp/map.h +++ b/src/core/lib/gprpp/map.h @@ -55,8 +55,25 @@ class Map { typedef Compare key_compare; class iterator; + Map() = default; ~Map() { clear(); } + // Movable. + Map(Map&& other) : root_(other.root_), size_(other.size_) { + other.root_ = nullptr; + other.size_ = 0; + } + Map& operator=(Map&& other) { + if (this != &other) { + clear(); + root_ = other.root_; + size_ = other.size_; + other.root_ = nullptr; + other.size_ = 0; + } + return *this; + } + T& operator[](key_type&& key); T& operator[](const key_type& key); iterator find(const key_type& k); diff --git a/test/core/gprpp/map_test.cc b/test/core/gprpp/map_test.cc index 30d9eb0b207..21aeee82486 100644 --- a/test/core/gprpp/map_test.cc +++ b/test/core/gprpp/map_test.cc @@ -437,6 +437,35 @@ TEST_F(MapTest, LowerBound) { EXPECT_EQ(it, test_map.end()); } +// Test move ctor +TEST_F(MapTest, MoveCtor) { + Map test_map; + for (int i = 0; i < 5; i++) { + test_map.emplace(kKeys[i], Payload(i)); + } + Map test_map2 = std::move(test_map); + for (int i = 0; i < 5; i++) { + EXPECT_EQ(test_map.end(), test_map.find(kKeys[i])); + EXPECT_EQ(i, test_map2.find(kKeys[i])->second.data()); + } +} + +// Test move assignment +TEST_F(MapTest, MoveAssignment) { + Map test_map; + for (int i = 0; i < 5; i++) { + test_map.emplace(kKeys[i], Payload(i)); + } + Map test_map2; + test_map2.emplace("xxx", Payload(123)); + test_map2 = std::move(test_map); + for (int i = 0; i < 5; i++) { + EXPECT_EQ(test_map.end(), test_map.find(kKeys[i])); + EXPECT_EQ(i, test_map2.find(kKeys[i])->second.data()); + } + EXPECT_EQ(test_map2.end(), test_map2.find("xxx")); +} + } // namespace testing } // namespace grpc_core