std::variant::valueless_by_exception

From cppreference.com
< cpplrm; | utilitylrm; | variant
constexpr bool valueless_by_exception() const noexcept;
(since C++17)

Returns false if and only if the variant holds a value.

Notes

A variant may become valueless in the following situations:

  • (guaranteed) an exception is thrown during the move initialization of the contained value from the temporary in copy assignment
  • (guaranteed) an exception is thrown during the move initialization of the contained value during move assignment
  • (optionally) an exception is thrown when initializing the contained value during a type-changing assignment
  • (optionally) an exception is thrown when initializing the contained value during a type-changing emplace

Since variant is never permitted to allocate dynamic memory, previous value cannot be retained in these situations.

This applies even to variants of non-class types:

struct S {
    operator int() { throw 42; }
};
variant<float, int> v{12.f}; // OK
v.emplace<1>(S()); // v may be valueless

A variant that is valueless by exception is treated as being in an invalid state: index returns variant_npos, get and visit throw bad_variant_access.