How to Design a Slimmer Vector of Variants in C++
summary
Starts from a real case where std::vector<std::variant<...>> blows up from ~20 KB to a theoretical minimum of 37 bytes and builds a working C++20 replacement that stores values contiguously with a bit‑packed index and a compact offset table that dynamically widens, yielding about 45 bytes in the demo and ~40–60% memory savings in benchmarks. Implementation uses PMR ideas, UBSan for alignment checks, and exposes do_get/visit APIs because subscript assignment can’t mutate in place; it is alignment‑safe but makes insert/erase and capacity semantics more complex.
AI-written summary · about
chapters (16)
- 0:00Introduction
- 2:55Vector of variant memory problem
- 7:08Heap allocation design
- 10:18Custom mixed-type vector
- 11:40Metadata: types and offsets
- 15:06Memory alignment challenges
- 19:15Correct alignment with alignof
- 22:03Bit packing metadata overhead
- 27:40Static vector and special members
- 30:27API for mixed-type storage
- 34:56Subscript operator assignment issues
- 43:20Subscript operator workarounds
- 45:05Runtime performance benchmark
- 48:14Memory usage benchmark
- 49:38Final design and challenges
- 51:22Q&A
related talks
01h 02mImplementing static_vector: How Hard Could it Be?
49mEnough TMP to write a Variant
41mEnough TMP to write a Variant
55mC++ Cache Friendly Data + Functional + Ranges = ❤️
01h 02mBreaking Dependencies - The Visitor Design Pattern in Cpp
06mLightning Talk: Cute Approach for Polymorphism in C++
49mApplied Modern C++: beyond type erasure and visitor pattern
01h 05mBetter C++ ranges
