Skip to content
Open
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
7 changes: 4 additions & 3 deletions universal/include/userver/utils/required.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
/// @brief @copybrief utils::Required

#include <concepts>
#include <memory>
#include <string_view>
#include <type_traits>
#include <utility>
Expand Down Expand Up @@ -31,7 +32,7 @@ class Required final {
Required() = delete;

/// @brief Construct `T` from a value (conditionally explicit).
template <typename U = T>
template <typename U>
requires(!std::same_as<std::decay_t<U>, Required> && std::constructible_from<T, U &&>)
constexpr explicit(!std::convertible_to<U&&, T>) Required(U&& value)
: value_(std::forward<U>(value))
Expand Down Expand Up @@ -59,10 +60,10 @@ class Required final {
constexpr T&& operator*() && noexcept { return std::move(value_); }

/// @brief Access members of the contained value.
constexpr T* operator->() noexcept USERVER_IMPL_LIFETIME_BOUND { return &value_; }
constexpr T* operator->() noexcept USERVER_IMPL_LIFETIME_BOUND { return std::addressof(value_); }

/// @overload
constexpr const T* operator->() const noexcept USERVER_IMPL_LIFETIME_BOUND { return &value_; }
constexpr const T* operator->() const noexcept USERVER_IMPL_LIFETIME_BOUND { return std::addressof(value_); }

/// @brief Implicit conversion to `T&`.
constexpr /*implicit*/ operator T&() & noexcept USERVER_IMPL_LIFETIME_BOUND { return value_; }
Expand Down
13 changes: 13 additions & 0 deletions universal/src/utils/required_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ TEST(UtilsRequired, DerefMove) {
EXPECT_EQ(moved, "move-me");
}

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

utils::Required<Overloaded> r{false};
EXPECT_FALSE(r->used);
}

TEST(UtilsRequired, Mutate) {
utils::Required<std::string> r{"initial"};
*r = "modified";
Expand Down
Loading