|
|
Member functions | ||||
Observers | ||||
optional::value | ||||
Iterators | ||||
(C++26) | ||||
(C++26) | ||||
Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
Modifiers | ||||
Non-member functions | ||||
Deduction guides | ||||
Helper classes | ||||
Helper objects | ||||
constexpr T& value()&; constexprconst T& value()const&; | (1) | (since C++17) |
constexpr T&& value()&&; constexprconst T&& value()const&&; | (2) | (since C++17) |
If*this contains a value, returns a reference to the contained value.
Otherwise, throws astd::bad_optional_access exception.
Contents |
(none)
A reference to the contained value.
std::bad_optional_access if*this does not contain a value.
The dereference operatoroperator*() does not check if this optional contains a value, which may be more efficient thanvalue()
.
#include <iostream>#include <optional> int main(){std::optional<int> opt={}; try{[[maybe_unused]]int n= opt.value();}catch(conststd::bad_optional_access& e){std::cout<< e.what()<<'\n';} try{ opt.value()=42;}catch(conststd::bad_optional_access& e){std::cout<< e.what()<<'\n';} opt=43;std::cout<<*opt<<'\n'; opt.value()=44;std::cout<< opt.value()<<'\n';}
Output:
bad optional accessbad optional access4344
returns the contained value if available, another value otherwise (public member function)[edit] | |
accesses the contained value (public member function)[edit] | |
(C++17) | exception indicating checked access to an optional that doesn't contain a value (class)[edit] |