From: Yedidya Feldblum Date: Fri, 26 Jun 2015 06:11:30 +0000 (-0700) Subject: to_shared_ptr. X-Git-Tag: v0.48.0~7 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=9b980c759b403c14ae34a74a060ad8a1ec7962b0;p=folly.git 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 --- 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 {};