How to disengage std::experimental::optional?

女生的网名这么多〃 提交于 2019-12-05 10:44:00
work = std::experimental::nullopt;

should disengage work.
The library fundamental TS specifies in [optional.nullopt]:

The struct nullopt_t is an empty structure type used as a unique type to indicate a disengaged state for optional objects.

There is an appropriate assignment operator, [optional.object.assign]:

optional<T>& operator=(nullopt_t) noexcept;

Effects: If *this is engaged calls val->T::~T() to destroy the contained value; otherwise no effect.

To avoid constructing a nullopt_t object every time, a constant of this type is already declared:

struct nullopt_t{see below};
constexpr nullopt_t nullopt(unspecified);

This simplest way to disengage an optional is with foo = {};, which is resolved as move assignment from a disengaged prvalue optional. The specification actually goes out of its way to enable this syntax which would otherwise be ambiguous with assignment from the contained type. (See [optional.object.assign] para 18-23 in N4023 for details)

Having read through the headers, the correct way to disengage the std::experimental::optional appears to be:

work = std::experimental::nullopt;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!