命名空间
变体
操作

std::optional<T>::reset

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
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 在 C++20 中,虽然非平凡析构在 constexpr 中是允许的,但 reset 不是 constexpr。 设为 constexpr

[编辑] 参阅

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