Namespaces
Variants

std::expected<T,E>::~expected

来自 zh.cppreference.net
 
 
 
 
constexpr ~expected();
(自 C++23 起)

主模板析构函数

销毁所含值:

  • 若 has_value() 为 true ,则销毁期望值。
  • 否则,销毁非期望值。

当 std:: is_trivially_destructible_v < T > 与 std:: is_trivially_destructible_v < E > 均为 true 时,该析构函数是平凡析构函数。

void 部分特化析构函数

如果 has_value() 为 false ,则销毁未期望值。

当 std:: is_trivially_destructible_v < E > 为 true 时,该析构函数是平凡析构函数。

示例

#include <expected>
#include <print>
void info(auto name, int x)
{
    std::println("{} : {}", name, x);
}
struct Value
{
    int o{};
    ~Value() { info(__func__, o); }
};
struct Error
{
    int e{};
    ~Error() { info(__func__, e); }
};
int main()
{
    std::expected<Value, Error> e1{42};
    std::expected<Value, Error> e2{std::unexpect, 13};
    std::expected<void, Error> e3{std::unexpect, 37};
}

输出:

~Error : 37
~Error : 13
~Value : 42