From 74a1c03549d4ae3374eba514b6bcb564e7779929 Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Fri, 21 Aug 2015 15:24:06 -0700 Subject: [PATCH] static_function_deleter. Summary: [Folly] static_function_deleter. So you can write this: using BIO_deleter = folly::static_function_deleter; auto buf = std::unique_ptr(BIO_new(BIO_s_mem())); buf = nullptr; In place of this: struct BIO_deleter { void operator()(BIO* bio) { BIO_free(bio); } }; auto buf = std::unique_ptr(BIO_new(BIO_s_mem())); buf = nullptr; Reviewed By: @alandau Differential Revision: D2364544 --- folly/Memory.h | 15 +++++++++++++++ folly/test/MemoryTest.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/folly/Memory.h b/folly/Memory.h index 70bc451c..76f11dc1 100644 --- a/folly/Memory.h +++ b/folly/Memory.h @@ -56,6 +56,21 @@ typename std::enable_if< std::extent::value != 0, std::unique_ptr>::type make_unique(Args&&...) = delete; +/** + * static_function_deleter + * + * So you can write this: + * + * using BIO_deleter = folly::static_function_deleter; + * auto buf = std::unique_ptr(BIO_new(BIO_s_mem())); + * buf = nullptr; // calls BIO_free(buf.get()) + */ + +template +struct static_function_deleter { + void operator()(T* t) { f(t); } +}; + /** * to_shared_ptr * diff --git a/folly/test/MemoryTest.cpp b/folly/test/MemoryTest.cpp index c9a2b0ea..03c53ee7 100644 --- a/folly/test/MemoryTest.cpp +++ b/folly/test/MemoryTest.cpp @@ -25,6 +25,35 @@ using namespace folly; +namespace { +class disposable { + public: + explicit disposable(std::function onDispose) : + onDispose_(std::move(onDispose)) {} + static void dispose(disposable* f) { + ASSERT_NE(nullptr, f); + f->onDispose_(); + delete f; + } + private: + std::function onDispose_; +}; +} + +TEST(static_function_deleter, example) { + size_t count = 0; + using disposable_deleter = + static_function_deleter; + make_unique([&] { ++count; }); + EXPECT_EQ(1, count); +} + +TEST(static_function_deleter, nullptr) { + using disposable_deleter = + static_function_deleter; + std::unique_ptr(nullptr); +} + TEST(shared_ptr, example) { auto uptr = make_unique("hello"); auto sptr = to_shared_ptr(std::move(uptr)); -- 2.34.1