std::optional

From cppreference.com
< cpp‎ | utility
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
optional
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
std::optional
Member functions
Observers
Monadic operations
Modifiers
Non-member functions
(C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20)
(C++17)
Deduction guides
Helper classes
(C++17)
(C++17)
(C++17)
Helper objects
(C++17)
(C++17)
 
Defined in header <optional>
template< class T >
class optional;
(since C++17)

The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.

A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T, bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.

Any instance of optional<T> at any given point in time either contains a value or does not contain a value.

If an optional<T> contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined.

When an object of type optional<T> is contextually converted to bool, the conversion returns true if the object contains a value and false if it does not contain a value.

The optional object contains a value in the following conditions:

  • The object is initialized with/assigned from a value of type T or another optional that contains a value.

The object does not contain a value in the following conditions:

  • The object is default-initialized.
  • The object is initialized with/assigned from a value of type std::nullopt_t or an optional object that does not contain a value.
  • The member function reset() is called.

There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. In addition, a program is ill-formed if it instantiates an optional with the (possibly cv-qualified) tag types std::nullopt_t or std::in_place_t.

Template parameters

T - the type of the value to manage initialization state for. The type must meet the requirements of Destructible (in particular, array and reference types are not allowed).

Member types

Member type Definition
value_type T

Member functions

constructs the optional object
(public member function)
destroys the contained value, if there is one
(public member function)
assigns contents
(public member function)
Observers
accesses the contained value
(public member function)
checks whether the object contains a value
(public member function)
returns the contained value
(public member function)
returns the contained value if available, another value otherwise
(public member function)
Monadic operations
(C++23)
returns the result of the given function on the contained value if it exists, or an empty optional otherwise
(public member function)
(C++23)
returns an optional containing the transformed contained value if it exists, or an empty optional otherwise
(public member function)
(C++23)
returns the optional itself if it contains a value, or the result of the given function otherwise
(public member function)
Modifiers
exchanges the contents
(public member function)
destroys any contained value
(public member function)
constructs the contained value in-place
(public member function)

Non-member functions

(C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20)
compares optional objects
(function template)
creates an optional object
(function template)
specializes the std::swap algorithm
(function template)

Helper classes

specializes the std::hash algorithm
(class template specialization)
(C++17)
indicator of optional type with uninitialized state
(class)
exception indicating checked access to an optional that doesn't contain a value
(class)

Helpers

(C++17)
an object of type nullopt_t
(constant)
in-place construction tag
(class template)

Deduction guides

Notes

Feature-test macro Value Std Comment
__cpp_lib_optional 201606L (C++17) std::optional
__cpp_lib_optional 202106L (C++20)
(DR)
Fully constexpr
__cpp_lib_optional 202110L (C++23) Monadic operations

Example

#include <iostream>
#include <optional>
#include <string>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
    if (b)
        return "Godzilla";
    return {};
}
 
// std::nullopt can be used to create any (empty) std::optional
auto create2(bool b)
{
    return b ? std::optional<std::string>{"Godzilla"} : std::nullopt;
}
 
int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';
 
    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create2(true))
        std::cout << "create2(true) returned " << *str << '\n';
}

Output:

create(false) returned empty
create2(true) returned Godzilla

See also

(C++17)
a type-safe discriminated union
(class template)
(C++17)
objects that hold instances of any CopyConstructible type
(class)