Commit 74a1c035 authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by facebook-github-bot-9

static_function_deleter.

Summary: [Folly] static_function_deleter.

So you can write this:

    using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free>;
    auto buf = std::unique_ptr<BIO, BIO_deleter>(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, BIO_deleter>(BIO_new(BIO_s_mem()));
    buf = nullptr;

Reviewed By: @alandau

Differential Revision: D2364544
parent 671368be
......@@ -56,6 +56,21 @@ typename std::enable_if<
std::extent<T>::value != 0, std::unique_ptr<T, Dp>>::type
make_unique(Args&&...) = delete;
/**
* static_function_deleter
*
* So you can write this:
*
* using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free>;
* auto buf = std::unique_ptr<BIO, BIO_deleter>(BIO_new(BIO_s_mem()));
* buf = nullptr; // calls BIO_free(buf.get())
*/
template <typename T, void(*f)(T*)>
struct static_function_deleter {
void operator()(T* t) { f(t); }
};
/**
* to_shared_ptr
*
......
......@@ -25,6 +25,35 @@
using namespace folly;
namespace {
class disposable {
public:
explicit disposable(std::function<void()> onDispose) :
onDispose_(std::move(onDispose)) {}
static void dispose(disposable* f) {
ASSERT_NE(nullptr, f);
f->onDispose_();
delete f;
}
private:
std::function<void()> onDispose_;
};
}
TEST(static_function_deleter, example) {
size_t count = 0;
using disposable_deleter =
static_function_deleter<disposable, &disposable::dispose>;
make_unique<disposable, disposable_deleter>([&] { ++count; });
EXPECT_EQ(1, count);
}
TEST(static_function_deleter, nullptr) {
using disposable_deleter =
static_function_deleter<disposable, &disposable::dispose>;
std::unique_ptr<disposable, disposable_deleter>(nullptr);
}
TEST(shared_ptr, example) {
auto uptr = make_unique<std::string>("hello");
auto sptr = to_shared_ptr(std::move(uptr));
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment