首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::optional::value

constexpr T& value() &; constexpr const T & value() const &;

(1)

(since C++17)

constexpr T&& value() &&; constexpr const T&& value() const &&;

(2)

(since C++17)

如果*this包含值,则返回对包含的值的引用。

否则,抛出一个std::bad_optional_access例外。

参数

%280%29

返回值

对包含的值的引用。

例外

std::bad_optional_access如果*this不包含值。

注记

去引用算子operator*()不检查此可选选项是否包含一个值,该值可能比value()...

二次

代码语言:javascript
复制
#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';
    }
}

二次

可能的产出:

二次

代码语言:javascript
复制
optional<T>::value: not engaged

二次

另见

value_or

returns the contained value if available, another value otherwise (public member function)

operator->operator*

accesses the contained value (public member function)

bad_optional_access (C++17)

exception indicating checked access to an optional that doesn't contain a value (class)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券