Type-Safe Variant Container with Explicit Lifetime Control

Hard · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Design a type-safe tagged union container SafeVariant<Args...> in C++ that stores at most one active value selected from its template parameter list Args..., and implement its runtime behavior in Python through safe_variant(operations, arguments) for automated evaluation.

C++ Container Specification

Your SafeVariant design models an inline, heap-free discriminated union with four guarantees:

  1. Inline Aligned Buffer: Allocate raw inline bytes using alignas on a std::byte buffer (or std::aligned_storage) sized to fit the largest alternative in Args..., paired with a size_t active-alternative tag so the footprint matches max(sizeof(Args...)) + sizeof(size_t) (subject to alignment padding).
  2. Active Tag & Checked Access: Track which alternative index currently occupies the buffer, starting in an uninitialized empty state. Calling get<T>() must raise a custom exception both when no value is stored and when T differs from the active alternative.
  3. Deterministic Destruction (RAII): Invoke the active alternative's destructor explicitly whenever set replaces a live value or ~SafeVariant() runs at scope exit.
  4. Strong Exception Guarantee on Assignment: If constructing the incoming object during set throws an exception, any previously stored value and its active type tag must remain completely intact.
template <typename... Args>
class SafeVariant {
public:
    SafeVariant();
    ~SafeVariant();

    template <typename T>
    void set(T&& val);

    template <typename T>
    T& get();
};

Python Evaluation Harness

Implement safe_variant(operations, arguments) to simulate a single SafeVariant instance starting empty and executing len(operations) calls in sequence:

def safe_variant(operations: List[str], arguments: List[List[object]]) -> List[object]:
    pass

Each step (operations[i], arguments[i]) is one of:

  • "set" with [type_name, value]: Destroys any currently stored object, stores value tagged with type_name, and appends None to the output list.
  • "get" with [requested_type]:
    • If the container holds no active value, appends {"error": "empty"}.
    • If an active value exists under a different type tag than requested_type, appends {"error": "type_mismatch"}.
    • Otherwise appends the currently stored value.
  • "fail_set" with []: Simulates an incoming constructor throwing an exception mid-set. Appends {"error": "construction_failed"} while leaving the prior state untouched.

Examples

Example 1

operations = ["set", "get", "set", "get", "get"]
arguments = [["int", 108], ["int"], ["string", "bolt"], ["string"], ["int"]]
# Output: [None, 108, None, "bolt", {"error": "type_mismatch"}]

Walk-through: First set stores 108 under "int" (None), and get("int") reads 108. Next set tears down 108 and stores "bolt" under "string" (None), so get("string") returns "bolt" while get("int") reports {"error": "type_mismatch"}.

Example 2

operations = ["get", "set", "get", "get"]
arguments = [["double"], ["double", 3.5], ["int"], ["double"]]
# Output: [{"error": "empty"}, None, {"error": "type_mismatch"}, 3.5]

Walk-through: Querying "double" before any successful write produces {"error": "empty"}. After set("double", 3.5) populates the slot, requesting "int" yields {"error": "type_mismatch"} without disturbing 3.5, which the final get("double") returns.

Example 3

operations = ["set", "fail_set", "get", "set", "get"]
arguments = [["string", "anchor"], [], ["string"], ["int", -9], ["int"]]
# Output: [None, {"error": "construction_failed"}, "anchor", None, -9]

Walk-through: set("string", "anchor") initializes the variant. When fail_set simulates a throwing constructor, it emits {"error": "construction_failed"} before altering storage, so get("string") still returns "anchor". A subsequent set("int", -9) cleanly replaces "anchor" with -9.

Constraints

  • All candidate types in Args... are copyable and movable.
  • 0 <= len(operations) == len(arguments) <= 10^5
  • Every "op" in operations is "set", "get", or "fail_set".
  • Falsy payloads such as 0 and "" are valid constructed values and must not be treated as an empty container.
  • Each operation in safe_variant should execute in O(1) time.

Step-by-step walkthrough

  1. Understand the C++ goal and the Python judge contract

    A variant (also called a tagged union or discriminated union) is a type-safe container that holds at most one value chosen from a fixed list of types — for instance, either an int or a std::string — inside a single shared block of memory.

    In C++, our SafeVariant<Args...> must enforce four guarantees:

    1. Single shared buffer: Reserve enough raw, properly aligned bytes for the largest type in Args..., plus one std::size_t index tracking which alternative is currently live (or that the variant is empty).
    2. Checked reads (get<T>()): Return a reference to the stored T when T is the active type; otherwise throw a custom exception distinguishing an empty variant from a wrong-type read.
    3. Explicit lifetimes (~SafeVariant() and set): Call the active object's destructor whenever a new value replaces it or the SafeVariant itself goes out of scope.
    4. Strong exception safety on set: If constructing the incoming object throws an exception, keep the previously held object alive and completely unchanged.

    In full C++ syntax with template arguments supplied, a typical lifecycle looks like:

    SafeVariant<int, std::string> v;
    v.set(108);
    int count = v.get<int>();        // Returns 108
    v.set<std::string>("bolt");      // Destroys 108, constructs std::string("bolt")
    

    Because the automated judge runs in Python, safe_variant(operations, arguments) tests this exact lifetime state machine through three operations:

    Operation    Arguments            Entry appended to output list
    ---------    ------------------   ----------------------------------------------------
    "set"        [type_name, value]   None  (destroys old value, stores new value)
    "get"        [type_name]          value, {"error": "empty"}, or {"error": "type_mismatch"}
    "fail_set"   []                   {"error": "construction_failed"}  (old value survives!)
    

    We will build the complete C++17 SafeVariant step by step first, then mirror its exact state machine in Python for the judge.

  2. Reserve raw, properly aligned storage plus an active-type tag

    Why not put int a; std::string b; inside a normal struct? Because a struct allocates space for every type simultaneously and default-constructs all of them even when unused. Why not use a bare C union? Because a bare union forgets which member is currently active, so it cannot throw on a wrong-type get or know whether its destructor must run ~std::string().

    Instead, SafeVariant owns an uninitialized array of std::byte and constructs one object inside it on demand using placement new — a C++ syntax (::new (ptr) T(...)) that constructs an object directly inside an existing memory buffer without allocating heap memory.

    Three pieces define the layout:

    • Buffer size: std::max({sizeof(Args)...}) finds the largest byte size across the variadic template pack Args....
    • Memory alignment: Every CPU type requires its starting memory address to be a multiple of some power of two (such as 4 for int or 8 for std::string). While alignas(std::max_align_t) aligns up to the largest standard scalar type (8 or 16 bytes), writing alignas(Args...) directly matches the exact strictest alignment among Args... — wasting zero extra padding on small types while still supporting over-aligned types like alignas(32) SIMD vectors.
    • Active index (index_): A std::size_t storing 0, 1, ... for the active type's position in Args..., or npos (size_t(-1)) when empty.
    Memory layout of SafeVariant<int, std::string> (on 64-bit libc++ where sizeof(string) == 24):
    
    +---------------------------------------------------+------------------+
    | storage_ : 24 raw bytes, aligned to 8 bytes       | index_ : 8 bytes |
    | [4 bytes of int + 20 unused] OR [24-byte string]  | 0, 1, or npos    |
    +---------------------------------------------------+------------------+
    Total size = max(4, 24) + 8 = 32 bytes (matching max(sizeof(Args...)) + sizeof(size_t))
    
    template <typename... Args>
    class SafeVariant {
    public:
        static constexpr std::size_t npos = static_cast<std::size_t>(-1);
        // ...
    private:
        alignas(Args...) std::byte storage_[std::max({sizeof(Args)...})];
        std::size_t index_ = npos;
    };
    

    (std::aligned_storage was the older C++11 spelling for raw aligned bytes, deprecated in C++23 in favor of alignas on a std::byte array.)

  3. Map types to indices at compile time and check them in `get<T>()`

    To translate a type T into its integer position in Args... at compile time, we write a small recursive type trait IndexOf<T, Args...>. If T matches the first type in the list, its index is 0; otherwise its index is 1 plus its index in the remaining types:

    Trace of IndexOf<std::string, int, std::string>::value:
      head is int != std::string   -> 1 + IndexOf<std::string, std::string>::value
      head is std::string (match!) -> 1 + 0 = 1
    
    // Primary declaration (intentionally undefined): if T is missing from Ts..., compilation fails!
    template <typename T, typename... Ts>
    struct IndexOf;
    
    // Base case: T is at the front of the list -> index 0.
    template <typename T, typename... Rest>
    struct IndexOf<T, T, Rest...> : std::integral_constant<std::size_t, 0> {};
    
    // Recursive step: First != T -> 1 + position of T in Rest...
    template <typename T, typename First, typename... Rest>
    struct IndexOf<T, First, Rest...>
        : std::integral_constant<std::size_t, 1 + IndexOf<T, Rest...>::value> {};
    

    Notice the compile-time safety bonus: calling v.get<double>() on SafeVariant<int, std::string> fails at compile time because IndexOf<double> hits the undefined primary template.

    At runtime, get<T>() checks two conditions in order:

    1. Is index_ == npos? Throw "empty".
    2. Is index_ != IndexOf<T, Args...>::value? Throw "type_mismatch".

    When both pass, it casts storage_ to T* and wraps the pointer in std::launder — a C++17 standard helper that tells the compiler's optimizer "a fresh object of type T was constructed in this byte buffer via placement new, so read the live object rather than stale assumptions about raw bytes."

    class BadVariantAccess : public std::logic_error {
    public:
        using std::logic_error::logic_error;
    };
    
    template <typename T>
    T& get() {
        if (index_ == npos) {
            throw BadVariantAccess("empty");
        }
        if (index_ != IndexOf<T, Args...>::value) {
            throw BadVariantAccess("type_mismatch");
        }
        return *std::launder(reinterpret_cast<T*>(storage_));
    }
    
  4. Destroy the active object safely by index (RAII)

    RAII (Resource Acquisition Is Initialization) is the core C++ principle that an object's destructor automatically releases whatever resources (such as heap memory inside std::string) that object owns when its lifetime ends. Because the compiler sees storage_ only as raw std::byte values, it will not call ~std::string() on its own — SafeVariant must invoke the active type's destructor explicitly.

    Only runtime index_ knows which alternative is alive, while each destructor ~T() is a compile-time per-type call. We connect them with std::index_sequence_for<Args...>, which generates the compile-time integer list 0, 1, ..., sizeof...(Args) - 1. Expanding a fold expression (destroy_if<Is, Args>(), ...) unrolls one if check per alternative:

    For SafeVariant<int, std::string>, destroy_active unrolls at compile time to:
      if (index_ == 0) std::launder(reinterpret_cast<int*>(storage_))->~int();
      if (index_ == 1) std::launder(reinterpret_cast<std::string*>(storage_))->~basic_string();
    
    void destroy() noexcept {
        if (index_ != npos) {
            destroy_active(std::index_sequence_for<Args...>{});
            index_ = npos;  // Immediately mark empty so we never double-destroy!
        }
    }
    
    template <std::size_t... Is>
    void destroy_active(std::index_sequence<Is...>) noexcept {
        (destroy_if<Is, Args>(), ...);
    }
    
    template <std::size_t I, typename T>
    void destroy_if() noexcept {
        if (index_ == I) {
            std::launder(reinterpret_cast<T*>(storage_))->~T();
        }
    }
    

    Two lifetime safeguards are essential here:

    • Reset index_ = npos immediately inside destroy(), so a later set or ~SafeVariant() can never run ~T() twice on dead bytes.
    • Delete compiler-generated raw-byte copying (SafeVariant(const SafeVariant&) = delete;), because copying storage_ byte-for-byte on a std::string shallow-copies its heap pointer and causes two variants to free the same memory! (Supporting variant copying requires dispatching to the active type's copy constructor via index_sequence, just like destroy_active.)
  5. Guarantee strong exception safety in `set()`: build temporary first

    Suppose v currently holds 108 (int), we call v.set(ThrowingType(...)), and ThrowingType's constructor throws an exception. Compare the two orders of operations:

    WRONG order (destroy first):
      1. destroy() wipes out 108
      2. ::new (storage_) U(val) THROWS! -> 108 is gone forever (or double-destroyed if index_ wasn't reset!)
    
    SAFE order (build temporary first -> strong exception guarantee):
      1. U temp(std::forward<T>(val));         -> If this THROWS, storage_ and index_ were never touched; 108 survives!
      2. destroy();                            -> Safely end 108's lifetime.
      3. ::new (storage_) U(std::move(temp));  -> noexcept move into storage_ (cannot throw).
      4. index_ = new_index;                   -> Record the new active type tag.
    

    Constructing temp first also makes self-assignment like v.set(v.get<std::string>()) safe: temp copies the string before destroy() tears down the original. Enforcing std::is_nothrow_move_constructible<U>::value at compile time guarantees Step 3 cannot fail after Step 2 has destroyed the previous object.

    Here is the complete C++17 SafeVariant:

    #include <algorithm>
    #include <cstddef>
    #include <new>
    #include <stdexcept>
    #include <type_traits>
    #include <utility>
    
    class BadVariantAccess : public std::logic_error {
    public:
        using std::logic_error::logic_error;
    };
    
    template <typename T, typename... Ts>
    struct IndexOf;
    
    template <typename T, typename... Rest>
    struct IndexOf<T, T, Rest...> : std::integral_constant<std::size_t, 0> {};
    
    template <typename T, typename First, typename... Rest>
    struct IndexOf<T, First, Rest...>
        : std::integral_constant<std::size_t, 1 + IndexOf<T, Rest...>::value> {};
    
    template <typename... Args>
    class SafeVariant {
        static_assert(sizeof...(Args) > 0, "SafeVariant requires at least one type");
    
    public:
        static constexpr std::size_t npos = static_cast<std::size_t>(-1);
    
        SafeVariant() noexcept = default;
        ~SafeVariant() { destroy(); }
    
        SafeVariant(const SafeVariant&) = delete;
        SafeVariant& operator=(const SafeVariant&) = delete;
    
        template <typename T>
        void set(T&& val) {
            using U = std::decay_t<T>;
            constexpr std::size_t new_index = IndexOf<U, Args...>::value;
            static_assert(std::is_nothrow_move_constructible<U>::value,
                          "SafeVariant requires a noexcept move constructor");
            U temp(std::forward<T>(val));                             // Phase 1: may throw safely
            destroy();                                                // Phase 2: destroy old value
            ::new (static_cast<void*>(storage_)) U(std::move(temp));  // Phase 3: noexcept commit
            index_ = new_index;
        }
    
        template <typename T>
        T& get() {
            if (index_ == npos) {
                throw BadVariantAccess("empty");
            }
            if (index_ != IndexOf<T, Args...>::value) {
                throw BadVariantAccess("type_mismatch");
            }
            return *std::launder(reinterpret_cast<T*>(storage_));
        }
    
        bool empty() const noexcept { return index_ == npos; }
    
    private:
        void destroy() noexcept {
            if (index_ != npos) {
                destroy_active(std::index_sequence_for<Args...>{});
                index_ = npos;
            }
        }
    
        template <std::size_t... Is>
        void destroy_active(std::index_sequence<Is...>) noexcept {
            (destroy_if<Is, Args>(), ...);
        }
    
        template <std::size_t I, typename T>
        void destroy_if() noexcept {
            if (index_ == I) {
                std::launder(reinterpret_cast<T*>(storage_))->~T();
            }
        }
    
        alignas(Args...) std::byte storage_[std::max({sizeof(Args)...})];
        std::size_t index_ = npos;
    };
    

    (Note on string literals: "bolt" has raw array type const char(&)[5], which std::decay_t turns into const char*. Calling v.set<std::string>("bolt") or v.set(std::string("bolt")) selects the std::string alternative cleanly.)

  6. Mirror the lifetime state machine in Python

    Now we translate our C++ class directly into Python for the automated judge:

    • self.active_type mirrors index_ (None corresponds to npos when empty).
    • self.storage_value mirrors storage_.
    • set runs the exact same three phases: check whether construction throws before calling _destroy(), then commit storage_value and active_type.
    • get checks self.active_type is None (never if not self.storage_value, which would misclassify 0 or "" as empty!), then checks self.active_type != requested_type.
    from typing import Optional
    
    
    class VariantError(Exception):
        """Carries the judge's runtime error code: 'empty', 'type_mismatch', or 'construction_failed'."""
    
        def __init__(self, code: str):
            super().__init__(code)
            self.code = code
    
    
    class SafeVariant:
        """Models a C++ discriminated union: one aligned storage slot plus an active-type tag."""
    
        def __init__(self):
            # active_type: str name of the live alternative (C++ `index_`), or None when empty (`npos`).
            # Example states: (None, None) when empty; ("int", 108) or ("string", "") when occupied.
            self.active_type: Optional[str] = None
            self.storage_value: object = None
    
        def _destroy(self) -> None:
            # Mirrors C++ `destroy()`: end the active object's lifetime and mark the variant empty.
            self.active_type = None
            self.storage_value = None
    
        def set(self, type_name: str, value: object, constructor_throws: bool = False) -> None:
            # Phase 1: Construct the incoming object in a temporary BEFORE touching current storage.
            # If construction throws, both `active_type` and `storage_value` remain untouched
            # (the strong exception guarantee).
            if constructor_throws:
                raise VariantError("construction_failed")
    
            # Phase 2: Explicitly destroy any previously held object before reusing storage.
            self._destroy()
    
            # Phase 3: Commit the newly built value into storage and record its active type tag.
            self.storage_value = value
            self.active_type = type_name
    
        def get(self, requested_type: str) -> object:
            # Check emptiness via `active_type is None`, never via truthiness of `storage_value`,
            # because falsy values like `0` and `""` are valid constructed objects.
            if self.active_type is None:
                raise VariantError("empty")
            if self.active_type != requested_type:
                raise VariantError("type_mismatch")
            return self.storage_value
    
  7. Replay the judge operations and trace Examples 1–3

    safe_variant creates one SafeVariant, executes each (op, args) pair in order, and turns any VariantError into {"error": err.code}:

    Example 1 trace:
      init                       -> state = (None, None)
      set("int", 108)            -> state = ("int", 108)          -> None
      get("int")                 -> "int" == "int"                -> 108
      set("string", "bolt")      -> destroys 108; ("string", "bolt") -> None
      get("string")              -> "string" == "string"          -> "bolt"
      get("int")                 -> "string" != "int"             -> {"error": "type_mismatch"}
    
    Example 2 trace (empty vs wrong type):
      init                       -> state = (None, None)
      get("double")              -> active_type is None           -> {"error": "empty"}
      set("double", 3.5)         -> state = ("double", 3.5)       -> None
      get("int")                 -> "double" != "int"             -> {"error": "type_mismatch"}
      get("double")              -> "double" == "double"          -> 3.5
    
    Example 3 trace (strong exception safety):
      init                       -> state = (None, None)
      set("string", "anchor")    -> state = ("string", "anchor")  -> None
      fail_set()                 -> throws in Phase 1!            -> {"error": "construction_failed"}
                                    state is STILL ("string", "anchor")
      get("string")              -> "string" == "string"          -> "anchor"
      set("int", -9)             -> destroys "anchor"; ("int", -9) -> None
      get("int")                 -> "int" == "int"                -> -9
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class VariantError(Exception):
        """Carries the judge's runtime error code: 'empty', 'type_mismatch', or 'construction_failed'."""
    
        def __init__(self, code: str):
            super().__init__(code)
            self.code = code
    
    
    class SafeVariant:
        """Models a C++ discriminated union: one aligned storage slot plus an active-type tag."""
    
        def __init__(self):
            # active_type: str name of the live alternative (C++ `index_`), or None when empty (`npos`).
            # Example states: (None, None) when empty; ("int", 108) or ("string", "") when occupied.
            self.active_type: Optional[str] = None
            self.storage_value: object = None
    
        def _destroy(self) -> None:
            # Mirrors C++ `destroy()`: end the active object's lifetime and mark the variant empty.
            self.active_type = None
            self.storage_value = None
    
        def set(self, type_name: str, value: object, constructor_throws: bool = False) -> None:
            # Phase 1: Construct the incoming object in a temporary BEFORE touching current storage.
            # If construction throws, both `active_type` and `storage_value` remain untouched
            # (the strong exception guarantee).
            if constructor_throws:
                raise VariantError("construction_failed")
    
            # Phase 2: Explicitly destroy any previously held object before reusing storage.
            self._destroy()
    
            # Phase 3: Commit the newly built value into storage and record its active type tag.
            self.storage_value = value
            self.active_type = type_name
    
        def get(self, requested_type: str) -> object:
            # Check emptiness via `active_type is None`, never via truthiness of `storage_value`,
            # because falsy values like `0` and `""` are valid constructed objects.
            if self.active_type is None:
                raise VariantError("empty")
            if self.active_type != requested_type:
                raise VariantError("type_mismatch")
            return self.storage_value
    
    
    def safe_variant(operations: List[str], arguments: List[List[object]]) -> List[object]:
        variant = SafeVariant()
        # results: one output per operation (None for set, held value for get, {"error": code} on throw).
        results: List[object] = []
    
        for op, args in zip(operations, arguments):
            try:
                if op == "set":
                    type_name = str(args[0])
                    new_value = args[1]
                    variant.set(type_name, new_value)
                    results.append(None)
                elif op == "get":
                    requested_type = str(args[0])
                    results.append(variant.get(requested_type))
                elif op == "fail_set":
                    # Simulates a C++ `T` constructor throwing mid-`set`: raises before mutating state.
                    variant.set("", None, constructor_throws=True)
                else:
                    raise ValueError(f"unknown operation: {op}")
            except VariantError as err:
                results.append({"error": err.code})
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a discriminated union (variant) — a type-safe container that holds at most one object from a fixed list of types — as a single reusable shipping crate with a label card clipped to the outside (index_ in C++, active_type in Python). The crate's interior is sized and aligned for the biggest, strictest item you might ever pack (std::max({sizeof(Args)...}) and alignas(Args...)), and the label card records whether the crate is currently "empty" (npos) or holds "int", "string", and so on. Whenever you replace what is inside, you first build the incoming item on a side workbench (temp); only after it finishes building without error do you recycle the old item (destroy()) and move the new item into the crate, giving the strong exception guarantee (an operation either succeeds completely or leaves the prior state untouched).

Why do simpler designs fail? Putting one member variable per type into a struct wastes memory for every unused type and forces all of them to be default-constructed up front. Using a bare C union shares memory, but forgets which type is inside — so reading the wrong type silently misinterprets raw bytes, and the destructor has no idea whether it needs to free a std::string's heap memory (RAII, Resource Acquisition Is Initialization, where destructors automatically release owned resources). Finally, if set destroys the old object before constructing the new one inside the buffer, a throwing constructor leaves the variant broken — losing the old value or even triggering a double-free later.

Here is a tiny 5-step walkthrough showing how the active tag and build-first rule work together:

Call                        State (active_type, storage)     Result
------------------------    ------------------------------   ---------------------------------
1. get("double")            (None, None)                     {"error": "empty"}
2. set("string", "anchor")  ("string", "anchor")             None
3. fail_set()               ("string", "anchor")  <-- safe!  {"error": "construction_failed"}
4. get("int")               ("string", "anchor")             {"error": "type_mismatch"}
5. get("string")            ("string", "anchor")             "anchor"

Complexity

  • Time: In the Python judge simulation, each set, get, and fail_set updates or checks two attributes in O(1) time, so replaying n operations takes O(n) total time. In the C++ SafeVariant<Args...>, get<T>() checks index_ in O(1) time (IndexOf is resolved entirely at compile time); set runs one construction of temp, one destructor on the previous active object, and one noexcept move, while destroy() checks index_ against the k template types (k is a small compile-time constant).
  • Space: O(1) auxiliary space per variant (O(n) only for the judge's results list of length n). In C++, each SafeVariant occupies max(sizeof(Args)...) + sizeof(std::size_t) bytes (rounded up to the strictest alignment of Args...), with zero heap allocations performed by the variant wrapper itself.

Edge cases

  • Reading an empty variant: get before any successful set raises "empty", distinct from "type_mismatch".
  • Failed construction on an already-empty variant: fail_set raises "construction_failed" and leaves the variant in the "empty" state.
  • Falsy values (0, "", False): Emptiness is determined strictly by active_type is None (index_ == npos in C++), never by if not value, so 0 and "" round-trip accurately.
  • Overwriting with the same type: set("int", 1) followed by set("int", 2) destroys 1 and constructs 2.
  • Self-assignment (v.set(v.get<std::string>())): Constructing temp before calling destroy() copies the active value while it is still alive, avoiding use-after-free.
  • Unlisted or decayed types in C++: Requesting get<double>() when double is not in Args... is a compile-time error; passing a string literal "bolt" (const char(&)[5], which decays to const char*) requires v.set<std::string>("bolt") or v.set(std::string("bolt")), and duplicate types in Args... should either be disallowed with a static_assert or resolved by index.

Common mistakes

  • Destroying the old object before constructing the new one: If the new type's constructor throws, the previous value has already been wiped out, violating the preservation requirement — and if index_ was not cleared first, ~SafeVariant() will run the dead object's destructor a second time.
  • Forgetting to reset index_ = npos inside destroy(): Any subsequent set or destructor call will invoke ~T() again on uninitialized bytes (undefined behavior).
  • Leaving C++'s compiler-generated copy constructor enabled: A default copy of std::byte storage_[] copies raw bytes rather than invoking std::string's copy constructor, causing two variants to alias and double-free the same heap buffer.
  • Assigning (*reinterpret_cast<T*>(storage_) = val) instead of placement new: Placement new (::new (ptr) T(...), constructing a fresh object inside an already-allocated buffer) starts an object's lifetime, whereas operator= assumes a live T object already exists at that address — for types like std::string, assigning over raw uninitialized bytes crashes immediately.
  • Forgetting std::launder or proper alignment: Memory alignment requires each type's address to be a multiple of a power of two; using a plain char buf[] without alignas(Args...) causes misaligned memory accesses, and omitting std::launder (which informs the C++17 optimizer that a new object now occupies the byte buffer) triggers lifetime undefined behavior.
  • Checking if not self.storage_value: in Python: Treats stored 0 or "" as an empty variant.

Alternative approaches

  • std::variant (C++17 standard library): Production C++ code should almost always use std::variant. Unlike our SafeVariant, std::variant default-constructs its first alternative (Args[0]) unless std::monostate is placed first, and if a type-changing assignment throws during move, it enters a special valueless_by_exception() state rather than guaranteeing the old value survives.
  • Double-buffered storage: Keeping two aligned byte buffers lets set construct the new object directly in the inactive buffer and flip an active-buffer bit, giving the strong exception guarantee even for types whose move constructor can throw — at the cost of doubling the variant's size (violating the max(sizeof(Args...)) + sizeof(size_t) size constraint).

Follow-up questions

  • How can the container construct held types in place when those types lack a default constructor? Our SafeVariant already avoids default-constructing any alternative at startup because storage_ is a raw std::byte array and index_ starts at npos. To construct a non-default-constructible (or even non-movable) type directly from constructor arguments without needing a pre-built object, add a variadic template method template <typename T, typename... CtorArgs> T& emplace(CtorArgs&&... ctor_args) (a template accepting any number of forwarded arguments). If T has a noexcept move constructor, emplace builds T temp(std::forward<CtorArgs>(ctor_args)...) first to keep the strong exception guarantee; if T is non-movable, emplace must call destroy() first (index_ = npos) and placement-new directly into storage_, providing the basic guarantee (valid empty variant if construction throws).
  • Which storage and access changes would allow get to execute at compile time inside a constexpr context? A constexpr (constant expression) function can be evaluated at compile time, where C++ strictly forbids reinterpret_cast on raw byte arrays. Replace std::byte storage_[] with a recursive variadic union (union Storage { Head head; Storage<Tail...> tail; }), where reading the currently active union member is allowed at compile time. Add constexpr (plus a const overload constexpr const T& get() const), keep the runtime index_ checks (throw expressions are legal on untaken branches in constexpr functions and turn wrong accesses into compile errors during constant evaluation), and recursively walk the union using if constexpr to return the member at IndexOf<T, Args...>::value (in C++20, std::construct_at and std::destroy_at also let set and ~SafeVariant be constexpr).
  • What happens when an alternative type requires stricter alignment than std::max_align_t, and how do stack and heap allocations stay aligned? Types such as SIMD vector registers (alignas(32)) or cache-line-padded structs (alignas(64)) exceed alignof(std::max_align_t) (typically 8 or 16 bytes), so aligning only to std::max_align_t would misalign them and cause hardware faults or undefined behavior. Using alignas(Args...) directly on storage_ gives both storage_ and the enclosing SafeVariant class the maximum alignment across all Args..., so stack and static variables are aligned automatically by the compiler. For heap allocations (new SafeVariant<...>), C++17 automatically invokes the over-aligned operator new(std::size_t, std::align_val_t) overload (whereas pre-C++17 code or custom memory pools using raw std::malloc must call std::aligned_alloc / custom operator new explicitly).

Follow-up questions

Similar questions

More Balyasny interview questions

All 4 Balyasny questions →