Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::optional::operator*: access the contained value

`*opt` returns a reference to the contained value. Check that `opt` has a value before dereferencing: index `0` is a valid result, not a missing one.

Version: ISO C++23; implementation support may vary

Syntax

// In <optional>, members of std::optional<T>:
constexpr T& operator*() & noexcept;
constexpr const T& operator*() const & noexcept;
constexpr T&& operator*() && noexcept;
constexpr const T&& operator*() const && noexcept;

// Use: *opt, with opt.has_value() == true.

std::optional::operator* is declared in <optional> and has been available since C++17. The expression *opt returns a reference to the object stored in a std::optional<T>; the call itself does not copy or move that object. This is neither indexing nor raw pointer dereference.

Check if (opt) or opt.has_value() before dereferencing. The contextual conversion to bool tests presence, not the stored value: index 0 passes the test, but an empty optional does not. In C++23, dereferencing an empty optional is undefined behavior. Do not rely on an implementation to detect the error. If absence should raise an exception, use opt.value(), which throws std::bad_optional_access when empty.

All four overloads are constexpr and noexcept. An lvalue optional gives T&, or const T& if the optional is const. An rvalue optional gives T&&, or const T&& if it is const. You can modify the stored object through T&; *std::move(opt) alone neither moves the object nor empties opt.

The returned reference does not extend the stored object's lifetime. Do not use it after opt.reset() or after opt is destroyed. A temporary optional is normally destroyed at the end of the full-expression that created it, but a separate reference binding to the optional itself can extend the optional's lifetime.

Examples

#include <cstddef>
#include <iostream>
#include <optional>

void print_index(const std::optional<std::size_t>& index)
{
    if (index) {
        std::cout << "index: " << static_cast<unsigned long long>(*index) << '\n';
    } else {
        std::cout << "not found\n";
    }
}

int main()
{
    const std::optional<std::size_t> first{0};
    const std::optional<std::size_t> missing{std::nullopt};
    print_index(first);
    print_index(missing);
}

Result

index: 0
not found

`if (index)` treats index `0` as present. For `std::nullopt`, the program prints `not found` without dereferencing.

Related lessons

  • C++ · Lesson 51 · Advanced · Version: 3

Sources