Namespaces
Variants

std::optional<T>:: value

From cppreference.net
Utilities library
constexpr T & value ( ) & ;
constexpr const T & value ( ) const & ;
(1) (seit C++17)
constexpr T && value ( ) && ;
constexpr const T && value ( ) const && ;
(2) (seit C++17)

Wenn * this einen Wert enthält, gibt es eine Referenz auf den enthaltenen Wert zurück.

Andernfalls wird eine std::bad_optional_access Exception ausgelöst.

Inhaltsverzeichnis

Parameter

(keine)

Rückgabewert

Eine Referenz auf den enthaltenen Wert.

Exceptions

std::bad_optional_access falls * this keinen Wert enthält.

Hinweise

Der Dereferenzierungsoperator operator*() überprüft nicht, ob dieses Optional einen Wert enthält, was effizienter sein kann als value() .

Beispiel

#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';
}

Ausgabe:

bad optional access
bad optional access
43
44

Siehe auch

gibt den enthaltenen Wert zurück, falls verfügbar, andernfalls einen anderen Wert
(öffentliche Elementfunktion)
greift auf den enthaltenen Wert zu
(öffentliche Elementfunktion)
Exception, die einen geprüften Zugriff auf ein optional angibt, das keinen Wert enthält
(Klasse)