From 67d26747cca6f8c563899857f820063221b77972 Mon Sep 17 00:00:00 2001 From: Susanne Pielawa <32822068+spielawa@users.noreply.github.com> Date: Tue, 9 Jan 2018 17:54:53 +0100 Subject: [PATCH] Implement assignment operator for common::optional. (#800) Implement assignment operator for common::optional. --- cartographer/common/optional.h | 14 ++++++++++++++ cartographer/common/optional_test.cc | 14 ++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/cartographer/common/optional.h b/cartographer/common/optional.h index 1f6c8d9..58e0a92 100644 --- a/cartographer/common/optional.h +++ b/cartographer/common/optional.h @@ -45,6 +45,20 @@ class optional { return *value_; } + optional& operator=(const T& other_value) { + this->value_ = common::make_unique(other_value); + return *this; + } + + optional& operator=(const optional& other) { + if (!other.has_value()) { + this->value_ = nullptr; + } else { + this->value_ = common::make_unique(other.value()); + } + return *this; + } + private: std::unique_ptr value_; }; diff --git a/cartographer/common/optional_test.cc b/cartographer/common/optional_test.cc index f7dcc7c..fbf96c9 100644 --- a/cartographer/common/optional_test.cc +++ b/cartographer/common/optional_test.cc @@ -44,6 +44,20 @@ TEST(OptionalTest, CreateFromOtherOptional) { EXPECT_EQ(5, b.value()); } +TEST(OptionalTest, AssignmentOperator) { + optional a(5); + optional b(4); + optional c; + a = b; + EXPECT_TRUE(a.has_value()); + EXPECT_EQ(4, a.value()); + a = c; + EXPECT_FALSE(a.has_value()); + a = 3; + EXPECT_TRUE(a.has_value()); + EXPECT_EQ(3, a.value()); +} + } // namespace } // namespace common } // namespace cartographer