std::optional<T>::operator->, std::optional<T>::operator*

Accesses the contained value.

# Declarations

constexpr const T* operator->() const noexcept;

(since C++17)

constexpr T* operator->() noexcept;

(since C++17)

constexpr const T& operator*() const& noexcept;

(since C++17)

constexpr T& operator*() & noexcept;

(since C++17)

constexpr const T&& operator*() const&& noexcept;

(since C++17)

constexpr T&& operator*() && noexcept;

(since C++17)

# Return value

Pointer or reference to the contained value.

# Notes

This operator does not check whether the optional contains a value! You can do so manually by using has_value() or simply operator bool(). Alternatively, if checked access is needed, value() or value_or() may be used.

# Example

#include <iomanip>
#include <iostream>
#include <optional>
#include <string>
 
int main()
{
    using namespace std::string_literals;
 
    std::optional<int> opt1 = 1;
    std::cout << "opt1: " << *opt1 << '\n';
 
    *opt1 = 2;
    std::cout << "opt1: " << *opt1 << '\n';
 
    std::optional<std::string> opt2 = "abc"s;
    std::cout << "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size() << '\n';
 
    // You can "take" the contained value by calling operator* on an rvalue to optional
 
    auto taken = *std::move(opt2);
    std::cout << "taken: " << std::quoted(taken) << "\n"
                 "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size()  << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2762C++17operator-> and operator* might be potentially-throwingmade noexcept

# See also