diff --git a/universal/include/userver/utils/optional_ref.hpp b/universal/include/userver/utils/optional_ref.hpp index 2462abb08af7..3890fc38a95c 100644 --- a/universal/include/userver/utils/optional_ref.hpp +++ b/universal/include/userver/utils/optional_ref.hpp @@ -3,6 +3,7 @@ /// @file userver/utils/optional_ref.hpp /// @brief @copybrief utils::OptionalRef +#include #include #include @@ -35,7 +36,7 @@ class OptionalRef { constexpr OptionalRef(const OptionalRef&) noexcept = default; constexpr OptionalRef& operator=(const OptionalRef&) noexcept = delete; - constexpr OptionalRef(T& other) noexcept : data_(&other) {} + constexpr OptionalRef(T& other) noexcept : data_(std::addressof(other)) {} // Forming a reference to a temporary is forbidden explicit constexpr OptionalRef(const T&&) = delete; @@ -101,12 +102,7 @@ class OptionalRef { "Attempt to initialize non-const T from a const optional value" ); - if (!other) { - return nullptr; - } - - auto& value = *other; - return &value; + return other.has_value() ? std::addressof(*other) : nullptr; } T* const data_ = nullptr; @@ -120,11 +116,6 @@ constexpr bool operator==(OptionalRef lhs, OptionalRef rhs) noexcept { return *lhs == *rhs; } -template -constexpr bool operator!=(OptionalRef lhs, OptionalRef rhs) noexcept { - return !(lhs == rhs); -} - } // namespace utils USERVER_NAMESPACE_END diff --git a/universal/src/utils/optional_ref_test.cpp b/universal/src/utils/optional_ref_test.cpp index 6eb112e67fb1..ce3912b57aa7 100644 --- a/universal/src/utils/optional_ref_test.cpp +++ b/universal/src/utils/optional_ref_test.cpp @@ -2,6 +2,8 @@ #include +#include + USERVER_NAMESPACE_BEGIN namespace { @@ -29,6 +31,27 @@ TEST(OptionalRef, Constructions) { static_assert(!std::is_constructible_v, int&>); } +TEST(OptionalRef, ConstructionsAddressof) { + struct Overloaded { + bool used = false; + auto operator& () { + used = true; + return this; + } + }; + + { + Overloaded over; + utils::OptionalRef ref(over); + EXPECT_FALSE(over.used); + } + { + std::optional over(std::in_place); + utils::OptionalRef ref(over); + EXPECT_FALSE(over->used); + } +} + TEST(OptionalRef, Values) { int a1_val = 1; int b1_val = 1;