Namespaces
Variants
Actions

std::optional<T>::value

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)  
(C++20)
(C++20)
(C++14)
(C++11)
(C++11)
(C++23)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)


 
 
constexpr T& value() &;
constexpr const T& value() const &;
(1) (since C++17)
constexpr T&& value() &&;
constexpr const T&& value() const &&;
(2) (since C++17)

If *this contains a value, returns a reference to the contained value.

Otherwise, throws a std::bad_optional_access exception.

[edit] Parameters

(none)

[edit] Return value

A reference to the contained value.

[edit] Exceptions

std::bad_optional_access if *this does not contain a value.

[edit] Notes

The dereference operator operator*() does not check if this optional contains a value, which may be more efficient than value().

[edit] Example

Run this code
#include <iostream>
#include <optional>
 
int main()
{
 std::optional <int> opt = {};
 
 try
 {
 [[maybe_unused]] int n = opt.value();
 }
 catch(const std::bad_optional_access & e)
 {
 std::cout << e.what() << '\n';
 }
 
 try
 {
 opt.value() = 42;
 }
 catch(const std::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 access
bad optional access
43
44

[edit] See also

returns the contained value if available, another value otherwise
(public member function) [edit]
accesses the contained value
(public member function) [edit]
exception indicating checked access to an optional that doesn't contain a value
(class) [edit]
Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/value&oldid=171476"

AltStyle によって変換されたページ (->オリジナル) /