easier rebinding of allocators
authorMarcelo Juchem <marcelo@fb.com>
Mon, 8 Apr 2013 20:38:22 +0000 (13:38 -0700)
committerJordan DeLong <jdelong@fb.com>
Sun, 21 Apr 2013 20:21:10 +0000 (13:21 -0700)
Summary: rebinding allocators is too cumbersome, this diff implements a helper to make this job easier.

Test Plan: unit test added

Reviewed By: tudorb@fb.com

FB internal diff: D766451

folly/Memory.h
folly/test/MemoryTest.cpp

index e4db242ba22edc24065a249e67bc5416f47944b3..0b6c0a11c333678caaf3b4de01f55e90436f21e2 100644 (file)
@@ -169,6 +169,18 @@ class StlAllocator {
   Alloc* alloc_;
 };
 
+/**
+ * Helper function to obtain rebound allocators
+ *
+ * @author: Marcelo Juchem <marcelo@fb.com>
+ */
+template <typename T, typename Allocator>
+typename Allocator::template rebind<T>::other rebind_allocator(
+  Allocator const &allocator
+) {
+  return typename Allocator::template rebind<T>::other(allocator);
+}
+
 /*
  * Helper classes/functions for creating a unique_ptr using a custom allocator
  *
index c9409d2206148247e31b0cc08258da1b1dbb6861..6397a0b9617ff25eefd28a9fb6f4d4982e419529 100644 (file)
@@ -58,6 +58,34 @@ TEST(StlAllocator, void_allocator) {
   ASSERT_EQ(nullptr, i.get());
 }
 
+TEST(rebind_allocator, sanity_check) {
+  std::allocator<long> alloc;
+
+  auto i = std::allocate_shared<int>(
+    rebind_allocator<int, decltype(alloc)>(alloc), 10
+  );
+  ASSERT_NE(nullptr, i.get());
+  EXPECT_EQ(10, *i);
+  i.reset();
+  ASSERT_EQ(nullptr, i.get());
+
+  auto d = std::allocate_shared<double>(
+    rebind_allocator<double>(alloc), 5.6
+  );
+  ASSERT_NE(nullptr, d.get());
+  EXPECT_EQ(5.6, *d);
+  d.reset();
+  ASSERT_EQ(nullptr, d.get());
+
+  auto s = std::allocate_shared<std::string>(
+    rebind_allocator<std::string>(alloc), "HELLO, WORLD"
+  );
+  ASSERT_NE(nullptr, s.get());
+  EXPECT_EQ("HELLO, WORLD", *s);
+  s.reset();
+  ASSERT_EQ(nullptr, s.get());
+}
+
 int main(int argc, char **argv) {
   FLAGS_logtostderr = true;
   google::InitGoogleLogging(argv[0]);