std::variant
can enter a state called "valueless by exception".
As I understand, the common cause of this is if a move assignment throws an exception. The variant's old value isn't guaranteed to be present anymore, and neither is the intended new value.
std::optional
, however, doesn't have such a state. cppreference makes the bold claim:
If an exception is thrown, the initialization state of *this ... is unchanged, i.e. if the object contained a value, it still contains a value, and the other way round.
How is std::optional
able to avoid becoming "valueless by exception", while std::variant
is not?
optional<T>
going fromT
to a differentT
state. Note thatemplace
andoperator=
have different behavior here in the case of an exception being thrown in the process! – Algebra