Namespaces
Variants

std::optional<T>::reset

来自 zh.cppreference.net
 
 
 
 
void reset() noexcept;
(C++17 起)
(C++20 起为 constexpr)

如果 *this 包含值,则销毁该值,如同通过 value().T::~T() 一样。否则,无任何效果。

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

注释

功能测试宏 值 标准 功能特性
__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++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
P2231R1 C++20 reset 不是 constexpr,而 C++20 允许在 constexpr 中进行非平凡析构 设为 constexpr

参见

赋值内容
(公开成员函数)