Commit 49926b98 authored by Shai Szulanski's avatar Shai Szulanski Committed by Facebook GitHub Bot

erased_unique_ptr

Summary: There are lots of unnecessary uses of shared_ptr for type erasure where refcounting is not needed because it is trivial to convert to shared_ptr<void>, while it is more involved to make the equivalent unique_ptr. Adds a utility that hides the details to bring effort parity between the two pointer types.

Reviewed By: yfeldblum

Differential Revision: D26323443

fbshipit-source-id: e33c5378f7df3105c7cb97d2622dca351b866035
parent 1e63a88c
......@@ -426,6 +426,29 @@ std::shared_ptr<remove_cvref_t<T>> copy_to_shared_ptr(T&& t) {
return std::make_shared<remove_cvref_t<T>>(static_cast<T&&>(t));
}
namespace detail {
template <typename T>
struct erased_unique_ptr_deleter {
static void call(void* ptr) { delete static_cast<T*>(ptr); }
};
} // namespace detail
/**
* to_erased_unique_ptr
*
* Wraps a raw pointer in a unique_ptr<void> with appropriate deleter.
* Makes it as easy to use as shared_ptr<void> when refcounting is not needed.
*/
using erased_unique_ptr = std::unique_ptr<void, void (*)(void*)>;
template <typename T>
erased_unique_ptr to_erased_unique_ptr(T* ptr) {
return {ptr, &detail::erased_unique_ptr_deleter<T>::call};
}
template <typename T>
erased_unique_ptr to_erased_unique_ptr(std::unique_ptr<T> ptr) {
return to_erased_unique_ptr(ptr.release());
}
/**
* SysAllocator
*
......
......@@ -174,6 +174,23 @@ TEST(copy_to_shared_ptr, example) {
EXPECT_EQ(17, *s);
}
TEST(to_erased_unique_ptr, example) {
erased_unique_ptr ptr = to_erased_unique_ptr(new int(42));
EXPECT_EQ(42, *static_cast<int*>(ptr.get()));
ptr = to_erased_unique_ptr(new std::string("foo"));
EXPECT_EQ("foo", *static_cast<std::string*>(ptr.get()));
struct {
int i;
} s;
ptr = to_erased_unique_ptr(new decltype(s){42});
EXPECT_EQ(42, static_cast<decltype(s)*>(ptr.get())->i);
ptr = to_erased_unique_ptr(std::make_unique<int>(42));
EXPECT_EQ(42, *static_cast<int*>(ptr.get()));
}
TEST(SysAllocator, equality) {
using Alloc = SysAllocator<float>;
Alloc const a, b;
......
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