From 2624a682280830b932a741c5386b58b4771b4f5e Mon Sep 17 00:00:00 2001 From: Marcelo Juchem Date: Mon, 8 Apr 2013 13:38:22 -0700 Subject: [PATCH] easier rebinding of allocators 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 | 12 ++++++++++++ folly/test/MemoryTest.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/folly/Memory.h b/folly/Memory.h index e4db242b..0b6c0a11 100644 --- a/folly/Memory.h +++ b/folly/Memory.h @@ -169,6 +169,18 @@ class StlAllocator { Alloc* alloc_; }; +/** + * Helper function to obtain rebound allocators + * + * @author: Marcelo Juchem + */ +template +typename Allocator::template rebind::other rebind_allocator( + Allocator const &allocator +) { + return typename Allocator::template rebind::other(allocator); +} + /* * Helper classes/functions for creating a unique_ptr using a custom allocator * diff --git a/folly/test/MemoryTest.cpp b/folly/test/MemoryTest.cpp index c9409d22..6397a0b9 100644 --- a/folly/test/MemoryTest.cpp +++ b/folly/test/MemoryTest.cpp @@ -58,6 +58,34 @@ TEST(StlAllocator, void_allocator) { ASSERT_EQ(nullptr, i.get()); } +TEST(rebind_allocator, sanity_check) { + std::allocator alloc; + + auto i = std::allocate_shared( + rebind_allocator(alloc), 10 + ); + ASSERT_NE(nullptr, i.get()); + EXPECT_EQ(10, *i); + i.reset(); + ASSERT_EQ(nullptr, i.get()); + + auto d = std::allocate_shared( + rebind_allocator(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( + rebind_allocator(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]); -- 2.34.1