From a695397e013de4596d05ca7fc1df2546ad639e64 Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Sun, 2 Jul 2017 10:22:33 -0700 Subject: [PATCH] In-place construction for Optional Summary: [Folly] In-place construction for `Optional`. Using `in_place` as the first argument. Avoid move operations. Reviewed By: Orvid, ot Differential Revision: D5362563 fbshipit-source-id: 771db2556842d5dec35d1bf2ad6c23358a417d54 --- folly/Optional.h | 7 +++++++ folly/test/OptionalTest.cpp | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/folly/Optional.h b/folly/Optional.h index 16cf86a1..c6980c18 100644 --- a/folly/Optional.h +++ b/folly/Optional.h @@ -61,6 +61,7 @@ #include #include +#include namespace folly { @@ -126,6 +127,12 @@ class Optional { construct(newValue); } + template + explicit Optional(in_place_t, Args&&... args) + noexcept(noexcept(::new (nullptr) Value(std::declval()...))) { + construct(std::forward(args)...); + } + void assign(const None&) { clear(); } diff --git a/folly/test/OptionalTest.cpp b/folly/test/OptionalTest.cpp index ed84f753..d075eeab 100644 --- a/folly/test/OptionalTest.cpp +++ b/folly/test/OptionalTest.cpp @@ -195,6 +195,21 @@ TEST(Optional, EmptyConstruct) { EXPECT_FALSE(bool(test2)); } +TEST(Optional, InPlaceConstruct) { + using A = std::pair; + Optional opt(in_place, 5, 3.2); + EXPECT_TRUE(bool(opt)); + EXPECT_EQ(5, opt->first); +} + +TEST(Optional, InPlaceNestedConstruct) { + using A = std::pair; + Optional> opt(in_place, in_place, 5, 3.2); + EXPECT_TRUE(bool(opt)); + EXPECT_TRUE(bool(*opt)); + EXPECT_EQ(5, (*opt)->first); +} + TEST(Optional, Unique) { Optional> opt; -- 2.34.1