##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::optional::value

From cppreference.com
< cpp‎ | utility‎ | optional

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 <optional>
    #include <iostream>
    int main()
    {
        std::optional<int> opt = {};

        try {
            int n = opt.value();
        } catch(const std::logic_error& e) {
            std::cout << e.what() << '\n';
        }
    }

Possible output:

    optional<T>::value: not engaged

### [edit] See also

value_or | returns the contained value if available, another value otherwise (public member function) [edit]
operator->operator* | accesses the contained value (public member function) [edit]
bad_optional_access (C++17) | exception indicating checked access to an optional that doesn't contain a value (class) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/value&oldid=89652"