How does std::variant manage its active alternative, and how should std::visit, get, and get_if be used safely?
Show answer and explanation
std::variant is a discriminated union that contains exactly one active alternative during normal operation and records its index. std::get<T> or get<I> returns the selected value but throws bad_variant_access when the requested alternative is inactive; get_if provides a nullable pointer for explicit probing. std::visit dispatches a callable over the active alternatives and forces the visitor to be valid for every possible combination. An exception while changing alternatives can leave a variant valueless_by_exception, so code that performs throwing conversions should handle that state rather than assuming an alternative is always available.
std::variant is a discriminated union that contains exactly one active alternative during normal operation and records its index. std::get<T> or get<I> returns the selected value but throws bad_variant_access when the requested alternative is inactive; get_if provides a nullable pointer for explicit probing. std::visit dispatches a callable over the active alternatives and forces the visitor to be valid for every possible combination. An exception while changing alternatives can leave a variant valueless_by_exception, so code that performs throwing conversions should handle that state rather than assuming an alternative is always available.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.