|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
| Iterators | ||||
(C++26) | ||||
(C++26) | ||||
| Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
| Modifiers | ||||
| Non-member functions | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
Defined in header <optional> | ||
template<class T> class optional; | (since C++17) | |
The class templatestd::optional manages an optional contained value, i.e. a value that may or may not be present.
A common use case foroptional is the return value of a function that may fail. As opposed to other approaches, such asstd::pair<T,bool>,optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.
Any instance ofoptional at any given point in time eithercontains a value ordoes not contain a value.
If anoptional contains a value, the value is guaranteed to benested within theoptional object. Thus, anoptional object models an object, not a pointer, even thoughoperator*() andoperator->() are defined.
When an object of typeoptional<T> iscontextually converted tobool, the conversion returnstrue if the object contains a value andfalse if it does not contain a value.
Theoptional object contains a value in the following conditions:
T or anotheroptional that contains a value.The object does not contain a value in the following conditions:
optional object that does not contain a value.The | (since C++26) |
There are no optional references, functions, arrays, or (possibly cv-qualified)void; a program is ill-formed if it instantiates anoptional with such a type. In addition, a program is ill-formed if it instantiates anoptional with the (possibly cv-qualified) tag typesstd::nullopt_t orstd::in_place_t.
Contents |
| T | - | the type of the value to manage initialization state for. The type must meet the requirements ofDestructible (in particular, array and reference types are not allowed). |
| Type | Definition |
value_type | T |
iterator(since C++26) | implementation-definedLegacyRandomAccessIterator,ConstexprIterator, andcontiguous_iterator whosevalue_type andreference arestd::remove_cv_t<T> andT&, respectively. |
const_iterator(since C++26) | implementation-definedLegacyRandomAccessIterator,ConstexprIterator, andcontiguous_iterator whosevalue_type andreference arestd::remove_cv_t<T> andconst T&, respectively. |
All requirements on the iterator types of aContainer apply to theiterator type ofoptional as well.
T*val | a pointer to the contained object (if exists) (exposition-only member object*) |
constructs theoptional object(public member function)[edit] | |
| destroys the contained value, if there is one (public member function)[edit] | |
| assigns contents (public member function)[edit] | |
Iterators | |
(C++26) | returns an iterator to the beginning (public member function)[edit] |
(C++26) | returns an iterator to the end (public member function)[edit] |
Observers | |
| accesses the contained value (public member function)[edit] | |
| checks whether the object contains a value (public member function)[edit] | |
| returns the contained value (public member function)[edit] | |
| returns the contained value if available, another value otherwise (public member function)[edit] | |
Monadic operations | |
(C++23) | returns the result of the given function on the contained value if it exists, or an emptyoptional otherwise(public member function)[edit] |
(C++23) | returns anoptional containing the transformed contained value if it exists, or an emptyoptional otherwise(public member function)[edit] |
(C++23) | returns theoptional itself if it contains a value, or the result of the given function otherwise(public member function)[edit] |
Modifiers | |
| exchanges the contents (public member function)[edit] | |
| destroys any contained value (public member function)[edit] | |
| constructs the contained value in-place (public member function)[edit] | |
(C++17)(C++17)(C++17)(C++17)(C++17)(C++17)(C++20) | comparesoptional objects(function template)[edit] |
(C++17) | creates anoptional object(function template)[edit] |
(C++17) | specializes thestd::swap algorithm (function template)[edit] |
(C++17) | hash support forstd::optional (class template specialization)[edit] |
(C++17) | indicator of anstd::optional that does not contain a value(class)[edit] |
(C++17) | exception indicating checked access to an optional that doesn't contain a value (class)[edit] |
(C++17) | an object of typenullopt_t(constant)[edit] |
| in-place construction tag (tag)[edit] |
template<class T> constexprboolranges::enable_view<std::optional<T>>=true; | (since C++26) | |
This specialization ofranges::enable_view makesoptional satisfyview.
template<class T> constexprauto format_kind<std::optional<T>>= range_format::disabled; | (since C++26) | |
This specialization offormat_kind disables therange formatting support ofoptional.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_optional | 201606L | (C++17) | std::optional |
202106L | (C++23) (DR20) | Fullyconstexpr | |
202110L | (C++23) | Monadic operations | |
__cpp_lib_optional_range_support | 202406L | (C++26) | Range support forstd::optional |
#include <iostream>#include <optional>#include <string> // optional can be used as the return type of a factory that may failstd::optional<std::string> create(bool b){if(b)return"Godzilla";return{};} // std::nullopt can be used to create any (empty) std::optionalauto 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 ifif(auto str= create2(true))std::cout<<"create2(true) returned "<<*str<<'\n';}
Output:
create(false) returned emptycreate2(true) returned Godzilla
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 4141 | C++17 | the requirement of storage allocation was confusing | the contained object must be nested within the optional object |
(C++17) | a type-safe discriminated union (class template)[edit] |
(C++17) | objects that hold instances of anyCopyConstructible type (class)[edit] |
(C++23) | a wrapper that contains either an expected or error value (class template)[edit] |
aview that contains a single element of a specified value(class template)(customization point object)[edit] | |
an emptyview with no elements(class template)(variable template)[edit] |