From 9b980c759b403c14ae34a74a060ad8a1ec7962b0 Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Thu, 25 Jun 2015 23:11:30 -0700 Subject: [PATCH] to_shared_ptr. Summary: [Folly] to_shared_ptr. So you can write this: auto sptr = to_shared_ptr(getSomethingUnique()); Instead of this: auto sptr = shared_ptr(getSomethingUnique()); Useful when `T` is long, such as `T = foobar::cpp2::FooBarServiceAsyncClient`. Reviewed By: @meyering Differential Revision: D2193572 --- folly/Memory.h | 23 +++++++++++++++++++++++ folly/test/MemoryTest.cpp | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/folly/Memory.h b/folly/Memory.h index b4d83e3c..70bc451c 100644 --- a/folly/Memory.h +++ b/folly/Memory.h @@ -56,6 +56,29 @@ typename std::enable_if< std::extent::value != 0, std::unique_ptr>::type make_unique(Args&&...) = delete; +/** + * to_shared_ptr + * + * Convert unique_ptr to shared_ptr without specifying the template type + * parameter and letting the compiler deduce it. + * + * So you can write this: + * + * auto sptr = to_shared_ptr(getSomethingUnique()); + * + * Instead of this: + * + * auto sptr = shared_ptr(getSomethingUnique()); + * + * Useful when `T` is long, such as: + * + * using T = foobar::cpp2::FooBarServiceAsyncClient; + */ +template +std::shared_ptr to_shared_ptr(std::unique_ptr&& ptr) { + return std::shared_ptr(std::move(ptr)); +} + /** * A SimpleAllocator must provide two methods: * diff --git a/folly/test/MemoryTest.cpp b/folly/test/MemoryTest.cpp index 3dc2afc2..c9a2b0ea 100644 --- a/folly/test/MemoryTest.cpp +++ b/folly/test/MemoryTest.cpp @@ -25,6 +25,13 @@ using namespace folly; +TEST(shared_ptr, example) { + auto uptr = make_unique("hello"); + auto sptr = to_shared_ptr(std::move(uptr)); + EXPECT_EQ(nullptr, uptr); + EXPECT_EQ("hello", *sptr); +} + template struct T {}; template struct S {}; template struct P {}; -- 2.34.1