When can a C++ std::variant become valueless_by_exception, and what do index(), std::get and std::visit do afterwards?
answer
- the old value is already gone
- a constructor throws mid-switch
- a sentinel index
- noexcept moves change the path
basics
~10 sA variant may become valueless when a type-changing emplace or assignment throws after the old alternative was destroyed. Then index() returns std::variant_npos, and std::get and std::visit throw std::bad_variant_access until a new value is assigned.
solid answer
~50 sSwitching alternatives means destroying the current one and constructing the new one in the same storage. If that construction throws, the old value is gone and the new one never existed, so the draft **permits** the variant to hold no value: `valueless_by_exception()` returns `true`, `index()` returns `std::variant_npos`, and `std::get` and `std::visit` throw `std::bad_variant_access`. Assigning or emplacing a new value recovers it. It cannot happen on default construction or when assigning the same alternative, whose own assignment runs instead. The converting assignment `v = x` is designed to avoid it: if constructing the new type from `x` may throw but its move constructor is `noexcept`, it builds a temporary first and then moves it in, so a throw leaves the old value intact. libstdc++ also avoids the state when every alternative is small and trivially copyable. `emplace` gives no such protection.
code
cpp · 31 lines#include <iostream>
#include <stdexcept>
#include <string>
#include <variant>
struct Payload { // copy may throw, move is noexcept
Payload() = default;
Payload(const Payload&) { throw std::runtime_error("copy failed"); }
Payload(Payload&&) noexcept = default;
Payload& operator=(const Payload&) = default;
Payload& operator=(Payload&&) noexcept = default;
};
struct Fragile { // copy may throw, no noexcept move
Fragile() = default;
Fragile(const Fragile&) { throw std::runtime_error("copy failed"); }
Fragile& operator=(const Fragile&) = default;
};
int main() {
std::variant<std::string, Payload> a = std::string("hello");
Payload p;
try { a = p; } catch (const std::exception& e) { std::cout << "a: " << e.what() << '\n'; }
std::cout << "a valueless: " << a.valueless_by_exception() << ", holds " << std::get<0>(a) << '\n';
std::variant<std::string, Fragile> b = std::string("hello");
Fragile f;
try { b = f; } catch (const std::exception& e) { std::cout << "b: " << e.what() << '\n'; }
std::cout << "b valueless: " << b.valueless_by_exception()
<< ", index is variant_npos: " << (b.index() == std::variant_npos) << '\n';
}go deeper
Know that the state exists, that index() returns std::variant_npos in it, and that std::get and std::visit throw std::bad_variant_access then.
Explain the destroy-then-construct sequence that causes it, which operations can trigger it, and why same-alternative assignment cannot.
Use the converting-assignment rule in your favour with noexcept move constructors, prefer assignment over emplace for throwing constructors, and treat a valueless variant as a symptom of swallowed exceptions.
Decide how much exception safety a message or document model needs, whether alternatives must be nothrow-movable by rule, and how such rules are enforced in review.
## Why the state exists `std::variant` stores its alternatives in one shared block of storage. Changing from alternative A to alternative B therefore takes two steps: destroy A, then construct B in the same bytes. If constructing B throws an exception, the variant is stuck: A is already destroyed and B never existed. Restoring A would need a copy kept somewhere, which would cost space or a heap allocation on every change, contrary to the type's design. The standard's answer is a documented failure state. After an exception during the **initialization of the contained value**, the variant "is permitted to not hold a value". In that state: | Operation | Result | |---|---| | `valueless_by_exception()` | `true` | | `index()` | `std::variant_npos` (the value `size_t(-1)`) | | `std::get<T>`, `std::get<I>` | throw `std::bad_variant_access` | | `std::get_if` | returns `nullptr` | | `std::visit` | throws `std::bad_variant_access` | | assignment or `emplace` of a value | recovers the variant | Comparisons treat a valueless variant as less than any variant with a value, and two valueless variants compare equal. ## Which operations can cause it 1. **`emplace<T>(args...)` with a throwing constructor.** The draft's own example uses a `variant<float, int>` and an argument whose conversion operator to `int` throws inside `emplace<1>`. 2. **Type-changing converting assignment `v = x`** in some cases, described below. 3. **Type-changing copy or move assignment** from another variant whose alternative's copy or move constructor throws, under the same kind of rule as converting assignment (copy assignment also builds a temporary first when the move is `noexcept`). It does **not** happen when the assignment keeps the same alternative: then the alternative's own assignment operator runs, and the draft says `valueless_by_exception()` stays `false`. Default construction either succeeds or throws out of the constructor, so no object exists to be valueless. ## How converting assignment tries to avoid it For `v = x` that selects alternative `Tj`, the draft chooses between two strategies: - If `is_nothrow_constructible_v<Tj, decltype(x)>` is `true`, **or** `Tj`'s move constructor is not `noexcept`, it constructs `Tj` directly in place (`emplace`). - Otherwise it first builds a **temporary** `Tj` from `x` and then moves it in with the `noexcept` move constructor. The second path means a throwing copy happens before the old value is touched. In a run with libc++, a `Payload` whose copy constructor throws but whose move constructor is `noexcept` left `std::variant<std::string, Payload>` holding `"hello"` after a failed `v = p;`. A `Fragile` type with the same throwing copy and **no** move constructor went valueless, with `index() == std::variant_npos`. ## Implementation differences The draft only *permits* the valueless state; implementations may avoid it more often. libstdc++ treats a variant as "never valueless" when every alternative is trivially copyable and at most 256 bytes (plus some library types it specializes), and then builds the new value in a temporary first. libc++ has no equivalent rule in its headers. Code must not rely on either: the portable assumption is "valueless is possible". ## What to do in production code - Give alternatives **`noexcept` move constructors**; it makes converting assignment safe and costs nothing for most types. - Prefer `v = T(args...)` over `v.emplace<T>(args...)` when a constructor can throw and the old value matters. - In visitors and switches, decide what a valueless message means: usually the exception that caused it is already propagating, so code that observes the state is often a `catch` handler that continued with a half-updated object. - Do not test `valueless_by_exception()` everywhere. Treat it like a moved-from object: rare, recoverable by assignment, and a sign that error handling swallowed an exception. Exception-safety guarantees in general are their own topic; the variant-specific point is that the strong guarantee is not free and the type documents exactly where it gives up.
- Why does std::variant not simply keep the old value when constructing the new one throws?Keeping it would need a second copy of the old value or a heap allocation for the new one on every type change, which breaks the design goal of in-place storage with no allocation. The draft instead permits a documented valueless state, reported by `valueless_by_exception()` and `variant_npos`, and makes converting assignment use a temporary when a `noexcept` move allows it cheaply.
- Can a variant whose alternatives are all int, double and enums become valueless?Their constructors cannot throw on their own, but `emplace` can still be given an argument whose conversion throws, as in the draft's example where a conversion operator to `int` throws inside `emplace<1>`. libstdc++ avoids the state when all alternatives are small and trivially copyable by building a temporary first; libc++ has no such rule, so portable code still treats it as possible.
- A default-constructed variant starts out valueless
- After a failed emplace the variant still holds its previous value
- valueless_by_exception means the variant holds std::monostate
- Assigning a value of the same alternative can make a variant valueless
- Once valueless, a variant can never hold a value again