Split get_default() into two for deferred default construction and added forwarding...
[folly.git] / folly / test / MapUtilTest.cpp
index 52e63e81f7a900360a54a6d3ccd5f0fc1cf2f4be..7ef13f718fcf757e50fc2e7a202bcbb118cabc01 100644 (file)
@@ -16,6 +16,7 @@
 
 #include <folly/MapUtil.h>
 
+#include <cstddef>
 #include <map>
 #include <unordered_map>
 
@@ -246,3 +247,52 @@ TEST(MapUtil, get_ref_default_path_temporary) {
   EXPECT_FALSE(GetRefDefaultPathCompiles<const int&&>::value);
   EXPECT_FALSE(GetRefDefaultPathCompiles<int&&>::value);
 }
+
+namespace {
+
+class TestConstruction {
+ public:
+  TestConstruction() {
+    EXPECT_TRUE(false);
+  }
+  TestConstruction(TestConstruction&&) {
+    EXPECT_TRUE(false);
+  }
+  TestConstruction(const TestConstruction&) {
+    EXPECT_TRUE(false);
+  }
+
+  explicit TestConstruction(std::string&& string)
+      : string_{std::move(string)} {}
+  explicit TestConstruction(int&& integer) : integer_{integer} {}
+
+  TestConstruction& operator=(const TestConstruction&) = delete;
+  TestConstruction& operator=(TestConstruction&&) = delete;
+
+  int integer_{};
+  std::string string_{};
+};
+
+} // namespace
+
+TEST(MapUtil, test_get_default_deferred_construction) {
+  auto map = std::unordered_map<int, TestConstruction>{};
+  map.emplace(
+      std::piecewise_construct,
+      std::forward_as_tuple(1),
+      std::forward_as_tuple(1));
+
+  EXPECT_EQ(map.at(1).integer_, 1);
+
+  {
+    auto val = get_default(map, 0, 1);
+    EXPECT_EQ(val.integer_, 1);
+    EXPECT_EQ(val.string_, "");
+  }
+
+  {
+    auto val = get_default(map, 0, "something");
+    EXPECT_EQ(val.integer_, 0);
+    EXPECT_EQ(val.string_, "something");
+  }
+}