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

来自cppreference.com
< cpp‎ | utility‎ | expected
 
 
 
 
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