std::optional<T>::value

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (哋它亢++20)
Dynamic memory management
Program utilities
Coroutine support (哋它亢++20)
Variadic functions
(哋它亢++20)
(哋它亢++26)
(哋它亢++11)
(哋它亢++20)
Debugging support
(哋它亢++26)
(哋它亢++26)
Three-way comparison
(哋它亢++20)(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)(哋它亢++20)(哋它亢++20)
General utilities
Date and time
Function objects
Formatting library (哋它亢++20)
(哋它亢++11)
Relational operators (deprecated in 哋它亢++20)
Integer comparison functions
(哋它亢++20)(哋它亢++20)(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)
Swap and type operations
(哋它亢++20)
(哋它亢++14)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
Common vocabulary types
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++23)
Elementary string conversions
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)


 
 
constexpr T& value() &;
constexpr const T& value() const &;
(1) (since 哋它亢++17)
constexpr T&& value() &&;
constexpr const T&& value() const &&;
(2) (since 哋它亢++17)

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

Otherwise, throws a std::bad_optional_access exception.

Parameters

(none)

Return value

A reference to the contained value.

Exceptions

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

Notes

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

Example

#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

See also

returns the contained value if available, another value otherwise
(public member function)
accesses the contained value
(public member function)
(哋它亢++17)
exception indicating checked access to an optional that doesn't contain a value
(class)