命名空间
变体
操作

std::optional<T>::reset

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
void reset() noexcept;
(自 C++17 起)
(constexpr 自 C++20 起)

如果 *this 包含一个值,则销毁该值,如同调用 value().T::~T()。 否则,没有效果。

在此调用之后,*this 不再包含值。

目录

[编辑] 注解

特性测试宏 Std 特性
__cpp_lib_optional 202106L (C++20)
(DR20)
完全 constexpr

[编辑] 示例

#include <iostream>
#include <optional>
 
struct A
{
    std::string s;
    A(std::string str) : s(std::move(str)) { std::cout << " constructed\n"; }
    ~A() { std::cout << " destructed\n"; }
    A(const A& o) : s(o.s) { std::cout << " copy constructed\n"; }
    A(A&& o) : s(std::move(o.s)) { std::cout << " move constructed\n"; }
 
    A& operator=(const A& other)
    {
        s = other.s;
        std::cout << " copy assigned\n";
        return *this;
    }
 
    A& operator=(A&& other)
    {
        s = std::move(other.s);
        std::cout << " move assigned\n";
        return *this;
    }
};
 
int main()
{
    std::cout << "Create empty optional:\n";
    std::optional<A> opt;
 
    std::cout << "Construct and assign value:\n";
    opt = A("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec.");
 
    std::cout << "Reset optional:\n";
    opt.reset();
    std::cout << "End example\n";
}

输出

Create empty optional:
Construct and assign value:
 constructed
 move constructed
 destructed
Reset optional:
 destructed
End example

[编辑] 缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
P2231R1 C++20 reset 在 C++20 中非平凡析构允许在 constexpr 中时不是 constexpr 设为 constexpr

[编辑] 参见

赋值内容
(公共成员函数) [编辑]