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

std::optional

Defined in header <optional>

template< class T > class optional;

(since C++17)

类模板std::optional管理任选包含的价值,即可能存在或不存在的价值。

通用用例optional可能失败的函数的返回值。与其他方法相反,例如std::pair<T,bool>,,,optional处理昂贵的构造对象很好,而且更易读,因为意图是显式表达的。

任何实例optional<T>在任何给定的时间点包含一个值不包含值。...

如果optional<T>包含一个值,则保证将该值作为optional对象占用,即从来没有发生动态内存分配。因此,optional对象建模对象,而不是指针,即使operator*()operator->()都被定义了。

当类型为可选的对象时<T>是上下文转换为bool,转换返回true如果对象包含一个值false如果不包含值。...

optional对象包含一个值在下列情况下:

  • 对象被初始化为类型的值。T
  • 对象是从另一个对象分配的。optional包含一个值...

对象不包含值。在下列情况下:

  • 对象是默认初始化的。
  • 对象的值为std::nullopt_t或者optional对象不包含值。...
  • 对象的值为std::nullopt_t或者从一个optional不包含值。

没有可选的引用,如果程序用引用类型实例化可选,则程序的格式不正确。

模板参数

T

-

the type of the value to manage initialization state for. The type must meet the requirements of Destructible

成员类型

Member type

Definition

value_type

T

成员函数

(constructor)

constructs the optional object (public member function)

(destructor)

destroys the contained value, if there is one (public member function)

operator=

assigns contents (public member function)

观察员

运算符->运算符%2A访问包含的值%28公共成员函数%29

操作者布拉斯[医]值检查对象是否包含值%28公共成员函数%29。

值返回包含的值%28公共成员函数%29。

价值[医]或返回包含的值(如果可用),否则返回另一个值%28公共成员函数%29。

修饰符

交换内容%28公共成员功能%29

重置销毁任何包含的值%28公共成员函数%29

构造包含的值inplace%28公共成员函数%29

非会员职能

operator==operator!=operator<operator<=operator>operator>= (C++17)

compares optional objects (function template)

make_optional (C++17)

creates an optional object (function template)

std::swap(std::optional) (C++17)

specializes the std::swap algorithm (function)

帮助者类

std::hash<std::optional> (C++17)

specializes the std::hash algorithm (class template specialization)

nullopt_t (C++17)

indicator of optional type with uninitialized state (class)

bad_optional_access (C++17)

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

帮手

nullopt (C++17)

an object of type nullopt_t (constant)

in_place in_place_type in_place_index in_place_t in_place_type_t in_place_index_t (C++17)

in-place construction tag (class template)

二次

代码语言:javascript
复制
#include <string>
#include <iostream>
#include <optional>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
    if(b)
        return "Godzilla";
    else
        return {};
}
 
int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';
 
    // optional-returning factory functions are usable as conditions of while and if
    if(auto str = create(true)) {
        std::cout << "create(true) returned " << *str << '\n';
    }
}

二次

产出:

二次

代码语言:javascript
复制
create(false) returned empty
create(true) returned Godzilla

二次

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

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

扫码关注腾讯云开发者

领取腾讯云代金券