Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 3 additions & 12 deletions universal/include/userver/utils/optional_ref.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/// @file userver/utils/optional_ref.hpp
/// @brief @copybrief utils::OptionalRef

#include <memory>
#include <optional>
#include <type_traits>

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -120,11 +116,6 @@ constexpr bool operator==(OptionalRef<T> lhs, OptionalRef<U> rhs) noexcept {
return *lhs == *rhs;
}

template <class T, class U>
constexpr bool operator!=(OptionalRef<T> lhs, OptionalRef<U> rhs) noexcept {
return !(lhs == rhs);
}

} // namespace utils

USERVER_NAMESPACE_END
23 changes: 23 additions & 0 deletions universal/src/utils/optional_ref_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#include <gtest/gtest.h>

#include <optional>

USERVER_NAMESPACE_BEGIN

namespace {
Expand Down Expand Up @@ -29,6 +31,27 @@ TEST(OptionalRef, Constructions) {
static_assert(!std::is_constructible_v<OptionalRef<short>, int&>);
}

TEST(OptionalRef, ConstructionsAddressof) {
struct Overloaded {
bool used = false;
auto operator& () {
used = true;
return this;
}
};

{
Overloaded over;
utils::OptionalRef<Overloaded> ref(over);
EXPECT_FALSE(over.used);
}
{
std::optional<Overloaded> over(std::in_place);
utils::OptionalRef<Overloaded> ref(over);
EXPECT_FALSE(over->used);
}
}

TEST(OptionalRef, Values) {
int a1_val = 1;
int b1_val = 1;
Expand Down
Loading