absl::optional_ref

A std::optional-like interface around a T*.

Synopsis

Declared in <absl/types/optional_ref.h>

template<typename T>
class optional_ref;

Description

Similar to C++26's std::optional<T&>, but it also permits construction from rvalues. It makes it easier for functions to accept nullable object addresses, regardless of whether they point to temporaries. It is trivially copyable and destructible, so it should be passed by value.

Type Aliases

NameDescription
value_type The referenced value type.

Member Functions

NameDescription
optional_ref [constructor]Constructors
operator= [deleted]Assignment is deleted; optional_ref is not assignable.
as_optional Represents the optional_ref as a std::optional.
as_pointer Represents the optional_ref as a T* pointer.
has_value Determines whether the optional_ref contains a value.
operator* Accesses the underlying value; undefined behavior if empty.
operator-> Accesses members of the underlying value; undefined behavior if empty.
value Returns a reference to the underlying value.
value_or Returns the value if present, otherwise default_value.

Deduction Guides

NameDescription
optional_ref<T> Deduces optional_ref<T> from a mutable lvalue.
optional_ref<T> Deduces optional_ref<T> from a mutable std::optional.
optional_ref<T> Deduces optional_ref<T> from a pointer.
optional_ref<T const> Deduces optional_ref<const T> from a const lvalue.
optional_ref<T const> Deduces optional_ref<const T> from a const std::optional.

Non-Member Functions

NameDescription
operator!=Tests whether two optional_refs differ.
operator!=Tests whether an optional_ref differs from a value.
operator!=Tests whether an optional_ref holds a value.
operator==Compares the referenced value of an optional_ref to a value.
operator==Tests whether an optional_ref is empty.
operator==Compares the referenced values of two optional_refs.