C++ Contiguous vs Node Containers and Polymorphic Dispatch
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
In a C++ systems engineering interview, walk through two core language and standard-library design topics:
- Contiguous resizable buffers vs. node-linked sequences: Contrast
std::vector<T>againststd::list<T>across heap storage geometry and per-element overhead, indexed lookup complexity and iterator categories, asymptotic versus real-world costs of inserting or erasing elements at endpoints and interior positions, CPU cache-line utilization and hardware prefetching, lifetime validity of iterators/pointers/references across container mutations, and concrete engineering scenarios that call for each container. - Polymorphism in C++: Define what polymorphic code achieves, contrast static compile-time resolution against dynamic runtime dispatch, explain how overload sets, templates, class inheritance, and
virtualmember functions fit into those two mechanisms, and describe architectural situations where runtime indirection pays for itself in production systems.
Scope & Expectations
- Quantify memory overhead and hardware cache effects (such as 64-byte cache lines versus dependent pointer chasing) to explain why asymptotic Big-O alone can mislead container choice.
- State precise C++ iterator, pointer, and reference invalidation rules—including capacity reallocation on
std::vectorand splicing stability onstd::list. - Distinguish compile-time monomorphization and overload resolution from vtable/vptr dynamic dispatch, highlighting essential C++ safety practices (
virtualdestructors,override, avoiding object slicing) and practical trade-offs.
Step-by-step walkthrough
Memory layout: one contiguous block vs scattered heap nodes
A dynamic array (
std::vector<T>) stores all of its elements side by side in one contiguous heap allocation, managed by a small three-word header (datapointer,size, andcapacity, 24 bytes on 64-bit platforms):size()is how many elements are currently constructed and live.capacity()is how many elements fit in the allocated block before a reallocation is needed; the slots betweensize()andcapacity()are raw uninitialized spare capacity.
A doubly linked list (
std::list<T>) stores each element in its own separate heap-allocated node alongside two pointers (prevandnext), so neighboring elements can live far apart in RAM:std::vector<int> (size = 3, capacity = 4): stack header [ data* | size=3 | cap=4 ] | v heap block: [ 10 | 20 | 30 | (spare) ] <-- one contiguous allocation std::list<int> (size = 3): sentinel [ next* | prev* ] | v node A @ 0x7100: [ prev | next | 10 | pad ] ---> node B @ 0x4a80: [ prev | next | 20 | pad ] | v node C @ 0x9f20: [ prev | next | 30 | pad ]Worked memory comparison for
1,000,000intvalues (4 bytes each) on 64-bit C++:std::vector<int> (with 2x capacity doubling, capacity = 2^20 = 1,048,576): 1,048,576 × 4 bytes ≈ 4.2 MB (21 heap allocations total) (or exactly 4.0 MB in 1 allocation if v.reserve(1'000'000) is called up front) std::list<int>: 1,000,000 nodes × (8-byte prev + 8-byte next + 4-byte int + 4-byte alignment padding = 24 bytes) = 24.0 MB raw node structs With standard allocator chunk rounding/metadata (32 B/node) ≈ 32.0 MB (1,000,000 allocations!)For small elements,
std::listuses roughly 6x–8x more memory and stresses the heap allocator with a million tiny allocations.Random access and iterator categories
Because a vector's elements sit side by side in memory, the address of element
iis computed in one arithmetic formula:data() + i * sizeof(T). Indexingv[i](unchecked) orv.at(i)(bounds-checked) runs in O(1) time. Vector iterators are random-access iterators—jumpingit + 1000is a single pointer addition.std::listintentionally omitsoperator[]because reaching thei-th element requires followingiseparatenextpointers in O(i) time. List iterators are bidirectional iterators (supporting only++itand--it), which restricts standard algorithms:std::sortrequires random-access iterators and will not compile onstd::list; you must call the member functionlist.sort()(an O(n log n) merge sort that relinks node pointers without moving elements).std::lower_bound(binary search) on a sortedstd::vectorruns in O(log n) time. Callingstd::lower_boundon a sortedstd::listperforms O(log n) element comparisons, but walksnextpointers O(n) times to find the midpoints—degrading to linear time!
std::vector<int> v = {10, 20, 30, 40}; int third_vec = v[2]; // O(1): base_ptr + 2 * sizeof(int) std::list<int> l = {10, 20, 30, 40}; int third_list = *std::next(l.begin(), 2); // O(i): chases two 'next' pointersInsertion and deletion trade-offs
Operation std::vector<T>std::list<T>Append / pop at back ( push_back,pop_back)Amortized O(1) / O(1) O(1) Insert / pop at front O(n): shifts all nelementsO(1) ( push_front,pop_front)Insert / erase at middle given an iterator O(n − pos): shifts trailing elements O(1): updates 4 neighbor pointers Search for a value + insert/erase O(n) scan + O(n) shift = O(n) O(n) scan + O(1) relink = O(n) Transfer nodes between containers O(k) moves + source tail shift splice: O(1) for 1 node or whole list; O(k) for k-node sub-range from another list(Note on
splice: since C++11,std::list::size()must be O(1), so splicing a[first, last)sub-range from a different list counts thoseknodes in O(k) to update both sizes; splicing within the same list stays O(1).)Why
vector::push_backis amortized O(1) (constant average cost per operation): Whensize() == capacity(),vectorallocates a block larger by a constant factor (2xin GCC's libstdc++ and Clang's libc++;1.5xin MSVC), moves existing elements over, and frees the old buffer. Over1,000,000pushes with2xdoubling, reallocations happen only at powers of two (1, 2, 4, ..., 524,288), moving1 + 2 + 4 + ... + 524,288 = 1,048,575elements in total—roughly 1 element move perpush_backon average! (Ifvectorgrew by a fixed+100slots each time, total moves would sum an arithmetic series to O(n²).)Two practical C++ nuances interviewers listen for:
list's O(1) middle insert/erase only applies when you already hold the iterator. If you have to scan frombegin()to find where to insert, both containers are O(n).- Mark move constructors
noexcept. During reallocation,std::vectoronly moves elements ifT's move constructor isnoexcept(orTis not copyable); otherwise it copies them so the old buffer stays intact if an exception is thrown partway through. - Bulk removal on a
vector: erasing elements in a loop one by one is O(n²); use the erase-remove idiom (std::erase/std::erase_ifin C++20) to compact kept elements in a single O(n) pass:
// Moves non-zero elements left in one O(n) pass, then trims the tail once: v.erase(std::remove(v.begin(), v.end(), 0), v.end()); // C++20: std::erase(v, 0);Cache locality: why vector often beats list even on O(n) inserts
Modern CPUs do not fetch individual 4-byte integers from main memory (DRAM); they fetch fixed 64-byte cache lines into fast CPU cache:
64-byte CPU cache line loaded from std::vector<int>: [ v[0] | v[1] | v[2] | v[3] | ... | v[14] | v[15] ] --> 16 useful ints per fetch! + Hardware prefetcher detects sequential addresses and pre-loads the next cache lines. 64-byte CPU cache line loaded from std::list<int>: [ prev* | next* | val | pad | unrelated heap data... ] --> 1 useful int per fetch! + Address of node i+1 lives INSIDE node i, stalling the CPU on each pointer load.An L1 cache hit takes roughly ~1 nanosecond (~3–4 CPU cycles), whereas a main-memory cache miss takes roughly ~70–100 nanoseconds (~200–300 cycles). Scanning a scattered
std::listis a chain of dependent loads—the CPU cannot even issue the memory read for nodei + 1until nodeiarrives from RAM—defeating both out-of-order execution and the hardware prefetcher (circuitry that predicts sequential address strides and fetches upcoming cache lines ahead of time).As a result, for small or trivially movable types (
int,double, small structs), inserting into the middle of astd::vectorof thousands of elements is frequently faster in wall-clock time than searching and inserting into astd::list: a sequential vector scan plus a contiguousmemmoveruns at peak cache bandwidth, while the list stalls on cache misses during its walk.Iterator invalidation rules and dangling-reference bugs
Iterator invalidation happens when modifying a container moves or destroys elements so existing iterators, raw pointers, or C++ references no longer point to valid objects; dereferencing them afterward causes undefined behavior (crashes, silent data corruption, or heisenbugs).
Mutating operation What std::vectorinvalidatesWhat std::listinvalidatespush_back/insertwith reallocation (size == capacity)Every iterator, pointer, and reference Never reallocates (none) push_backwithout reallocation (size < capacity)Only end()(elements do not move)None insert/erasewithout reallocation atposEverything at or after pos(includingend())insert: none;erase: only the erased element(s)reserve(new_cap)whennew_cap > capacity()Every iterator, pointer, and reference Not applicable splice,list::sort,reverseNot applicable None (nodes are relinked in place!) The most common production C++ bug with
std::vectoris holding an element reference across apush_backor incrementing an invalidated iterator aftererase:std::vector<int> v = {1, 2, 3}; int& first = v[0]; v.push_back(4); // Reallocates if capacity was 3 -> 'first' now dangles into freed RAM! // int bad = first; // Undefined behavior! // Safe single-element loop erasure: erase() returns the iterator to the next element for (auto it = v.begin(); it != v.end(); ) { if (*it % 2 == 0) { it = v.erase(it); } else { ++it; } }Typical use cases: when to pick vector vs list
- Choose
std::vectoras your default sequential container (95%+ of cases): dense computation, order-book price levels, sorting, binary search, stacks, serialization buffers, and interoperating with C APIs expecting(ptr, len)viav.data(). - Choose
std::listonly when you specifically need pointer/iterator stability or node splicing:- Stable iterators stored in an index, such as an LRU (Least Recently Used) cache combining
std::unordered_map<Key, std::list<Node>::iterator>with astd::list<Node>: every cache hit moves the accessed node to the front in O(1) vialist.splice(list.begin(), list, it)without invalidating any iterator in the hash map. - O(1) splicing of whole queues between subsystems (e.g., detaching a batch of log entries from a lock-protected producer list into a consumer list in a few pointer swaps).
- Non-movable, non-copyable objects (e.g., structs containing a
std::mutexorstd::atomic) constructed in place viaemplace_back, sincevectorreallocation requires moving or copying elements.
- Stable iterators stored in an index, such as an LRU (Least Recently Used) cache combining
- Keep nearby containers in mind:
std::dequeprovides O(1)push_frontandpush_backplus O(1) random access using fixed-size chunks (preserving element references on end-pushes, though invalidating iterators), andstd::forward_listcuts node overhead to one pointer when backward traversal is unnecessary.
- Choose
Compile-time polymorphism: overloading and templates
Polymorphism ("many forms") lets a single interface operate on multiple concrete types. C++ separates polymorphism by when the target function is chosen.
In compile-time (static) polymorphism, the compiler resolves the exact function to call from the expressions' static types (the types known in source code at compile time). There is zero runtime dispatch overhead, and the compiler can inline the callee directly into hot loops:
- Function and operator overloading (ad-hoc polymorphism): multiple functions share one name with different parameter lists (
abs(int)vsabs(double), oroperator+on numbers vs strings), selected by compile-time overload resolution. - Templates (parametric polymorphism): a single function or class template works for any type
Tsatisfying the syntactic operations used inside it (constrained cleanly at the signature in C++20 using concepts). The compiler generates specialized machine code per concrete typeT(monomorphization), trading faster execution for longer compile times and larger binaries if instantiated across many types. - CRTP (Curiously Recurring Template Pattern): a class
Derivedinherits fromBase<Derived>soBasecan callstatic_cast<Derived*>(this)->impl()at compile time withoutvirtualoverhead.
// Function overloading: picked at compile time from the argument type void log_value(int x) { std::cout << "int: " << x << '\n'; } void log_value(const std::string& s) { std::cout << "str: " << s << '\n'; } // Function template: compiler stamps out a separate version per Shape type template <typename Shape> double sum_areas(const std::vector<Shape>& shapes) { double total = 0.0; for (const auto& s : shapes) { total += s.area(); // direct, inlinable call — no virtual table lookup } return total; }Limitation:
std::vector<Shape>is homogeneous—every element must be the exact same compile-time typeShape. Static polymorphism alone cannot store mixedCircleandSquareobjects in one vector or instantiate a handler chosen from a runtime config file.- Function and operator overloading (ad-hoc polymorphism): multiple functions share one name with different parameter lists (
Runtime polymorphism: inheritance, virtual functions, and practical use
In runtime (dynamic) polymorphism, a base class declares methods
virtual, derived classes override them (override), and callers invoke them through a base-class pointer or reference (Shape*,const Shape&). The program chooses which override to execute at runtime based on the object's true dynamic type (dynamic dispatch).Compilers implement dynamic dispatch using a vtable (a per-class read-only table of function pointers) and a hidden vptr (an 8-byte pointer stored at the start of every polymorphic object instance):
Heap objects pointed to by std::vector<std::unique_ptr<Shape>>: shapes[0] ---> [ vptr* | radius = 2.0 ] ---> Circle vtable: [0] &Circle::~Circle [1] &Circle::area shapes[1] ---> [ vptr* | side = 3.0 ] ---> Square vtable: [0] &Square::~Square [1] &Square::areastruct Shape { virtual double area() const = 0; // pure virtual ('= 0') makes Shape an abstract interface virtual ~Shape() = default; // MUST be virtual whenever deleting via Shape*! }; struct Circle final : Shape { double radius; explicit Circle(double r) : radius(r) {} double area() const override { return 3.141592653589793 * radius * radius; } }; struct Square final : Shape { double side; explicit Square(double s) : side(s) {} double area() const override { return side * side; } };Essential C++ rules for runtime polymorphism:
- Always give polymorphic base classes a
virtualdestructor: withoutvirtual ~Shape(), deleting aCirclethrough aShape*(std::unique_ptr<Shape>) triggers undefined behavior and leaks resources owned byCircle. - Avoid object slicing: passing or storing a derived object by value (
Shape s = Circle(2.0);) copies only theShapesubobject, stripping offCircle's fields and vptr. Always pass polymorphic objects by reference or smart pointer. - Mark overrides
override(and leaf classesfinal):overrideturns signature mismatches (like forgettingconst) into compile errors instead of silent overload hiding, whilefinalhelps the compiler devirtualize calls back into direct inlined calls when the concrete type is visible. - No dynamic dispatch into derived classes inside constructors/destructors: while
Base::Base()is running, the derived members are not constructed yet (or in~Base(), already destroyed), so virtual calls resolve toBase's own version.
When dynamic dispatch is useful in practice: Use
virtualinterfaces when concrete types arrive at runtime (message handlers selected from network headers, UI widgets, AST nodes), when maintaining open heterogeneous collections or plugin systems where new derived types are added without recompiling existing callers, or at architectural boundaries for dependency injection (swapping a liveExchangeGatewaywith aMockGatewayin unit tests). When the set of types is small, fixed, and known at compile time,std::variant<Circle, Square>withstd::visitachieves runtime dispatch without per-object heap allocations, keeping mixed values contiguous inside a singlestd::vector!- Always give polymorphic base classes a
Intuition & how it works
Picture std::vector as a row of numbered apartment mailboxes bolted onto one wall, and std::list as a scavenger hunt where each envelope sits in a different building across town with a note pointing to the next address. With the mailbox wall (vector), jumping straight to box #500 is instant math (start + 500 * box_width), and your mail carrier loads 16 neighboring boxes at a time in one armful (cache locality). With the scavenger hunt (list), reaching #500 forces 500 separate trips across town, though slipping a new envelope between two envelopes you are already holding only requires rewriting two address notes instead of sliding every later mailbox over.
A beginner trap is trusting textbook Big-O in isolation—assuming std::list is faster whenever a program inserts or deletes in the middle. On real CPUs, finding where to insert in a std::list stalls on slow main-memory pointer hops (~70–100 ns per cache miss vs ~1 ns in L1 cache), whereas scanning a std::vector and shifting contiguous ints with memmove streams smoothly through 64-byte CPU cache lines. Similarly, C++ polymorphism ("one interface, many types") splits into two tools: compile-time polymorphism (templates and overloading, like stamping custom wrenches in the factory with zero runtime cost) versus runtime polymorphism (virtual functions, like a universal socket adapter that checks which attachment is plugged in at runtime via a hidden function-pointer table).
Walk through two concrete mini-examples to compare both ideas:
- Inserting
25into{10, 20, 30, 40}:std::vectorscans[10, 20, 30, 40]inside a single 64-byte cache line, shifts30and40four bytes right, and writes25at index2(invalidating iterators from index2onward, or all iterators ifsize == capacitytriggers a2xbuffer reallocation).std::listchases heap pointers node by node to reach30, allocates a new 24-byte node[prev | next | 25], and rewires four neighbor pointers—slower to reach the spot, but every existing iterator into the list stays valid. - Computing
area()on shapes:template <typename S> double twice(const S& s) { return 2 * s.area(); }resolvess.area()at compile time with zero indirection, whereasstd::vector<std::unique_ptr<Shape>>holding aCircle(2)andSquare(3)follows each object's hiddenvptrat runtime to its classvtableto dispatchCircle::area()(12.57) andSquare::area()(9.0).
Key points
- Memory layout and overhead:
std::vector<T>owns one contiguous heap block with sparecapacity();std::list<T>allocates one heap node per element containingprevandnextpointers. For1,000,0004-byteints on 64-bit C++,vectoruses ~4.2 MB in ~21 allocations versus ~24–32 MB across 1,000,000 allocations forlist. - Random access and algorithms:
vectorprovides O(1) indexing (data() + i * sizeof(T)) and random-access iterators, enabling O(n log n)std::sortand O(log n)std::lower_boundbinary search;listhas O(i) traversal and bidirectional iterators (++/--only), requiring memberlist::sort(). - Insertion and erasure trade-offs:
vector::push_backruns in amortized O(1) time (doubling capacity moves roughly 1 element per push on average, or 0 moves afterreserve(n)), while middle insert/erase shiftsn − poselements in O(n);listgives O(1) insert, erase, andspliceonly when you already hold an iterator to the target node. - Cache locality dominates small elements: a 64-byte CPU cache line packs 16 contiguous
ints and lets the hardware prefetcher preload upcoming lines, whereaslisttraversal performs dependent pointer loads that frequently miss cache. - Iterator invalidation:
vectorinvalidates all iterators, pointers, and references on reallocation, and invalidates those at or afterposon non-reallocatinginsert/erase(onlyend()on non-reallocatingpush_back);listnever invalidates iterators or references except to erased nodes. - Default to
vector, specialize withlist: usevectoralmost everywhere; picklistwhen an external map stores persistent node iterators (like an LRU cache usingunordered_map+list::splice), when splicing whole queues in O(1), or when holding non-movable objects. - Compile-time vs runtime polymorphism: function/operator overloading and templates resolve calls at compile time from static types (enabling inlining and zero memory overhead, constrained cleanly via C++20 concepts, but limited to homogeneous containers), whereas inheritance +
virtualfunctions dispatch at runtime on the dynamic type via an objectvptrand classvtable(enabling open heterogeneous collections, plugins, and runtime interfaces at the cost of an indirect call and an 8-bytevptrper object).
Common mistakes
- Claiming
std::listis faster for random middle insertions without already having the iterator. If you have to search linearly to find the insertion point first,vector's cache-friendly scan +memmoveusually beatslist's pointer-chasing walk for small or cheap-to-move types. - Keeping pointers, references, or iterators into a
std::vectoracrosspush_backorinsert. Any reallocation frees the old buffer and leavesint& ref = v[0]dangling into freed memory (undefined behavior). - Confusing
v.reserve(n)withv.resize(n).reserve(n)only pre-allocates raw sparecapacity()whilesize()stays0, so indexingv[0]afterreservewithout pushing or resizing is out-of-bounds undefined behavior. - Omitting
virtual ~Base() = default;on a polymorphic base class. Deleting aDerivedinstance through aBase*(includingstd::unique_ptr<Base>) without a virtual destructor is undefined behavior and skipsDerived's destructor. - Object slicing by passing or storing polymorphic types by value. Writing
std::vector<Shape>orvoid draw(Shape s)copies only theBasesubobject and discards derived data and overrides; use references (const Shape&) or smart pointers (std::unique_ptr<Shape>). - Calling virtual methods inside a constructor expecting the derived override to run. During
Base::Base(), theDerivedpart is not yet initialized, so C++ intentionally binds virtual calls toBase's implementation.
Follow-up questions
- How does std::deque balance endpoint growth, indexed lookup, and reference lifetime compared with std::vector and std::list?
std::dequestores elements in an indexed map of fixed-size contiguous chunks (such as 512 bytes or 4 KiB per block), providing O(1)push_frontandpush_backalongside O(1) random-access indexing (d[i]). Unlikevector, pushing at either end of adequenever reallocates or moves existing elements—so C++ pointers and references to existing elements remain valid, even though iterators are invalidated—at the cost of double pointer indirection on indexing and no single contiguousdata()buffer for C APIs. - Where does the real performance cost of a virtual method call come from on modern CPUs, and when can the compiler remove it? A virtual call loads the object's
vptr, loads the target function pointer from thevtable, and executes an indirect jump; on modern CPUs with warm branch predictors, that indirect jump adds only a few cycles unless mixed types cause mispredictions, but the bigger cost is blocking compiler inlining and SIMD loop vectorization. Marking leaf classes or overridesfinaland enabling Link-Time Optimization (LTO) lets the compiler prove the concrete dynamic type (devirtualization) and turn the virtual call back into a direct, inlined call. - In what scenarios is std::variant paired with std::visit preferable to a virtual base-class hierarchy? Choose
std::variant<Circle, Square>when the set of alternative types is closed and known at compile time: astd::vector<std::variant<Circle, Square>>stores heterogeneous shapes inline in one contiguous cache-friendly buffer with value semantics, zero per-object heap allocations, and novptroverhead (though each slot is sized to the largest alternative plus a tag byte). Choosevirtualinheritance when the set of types is open (such as plugins or independently compiled modules) or when alternative sizes vary wildly so padding every element to the largest type would waste memory.
Follow-up questions
- How does std::deque balance endpoint growth, indexed lookup, and reference lifetime compared with std::vector and std::list?
- Where does the real performance cost of a virtual method call come from on modern CPUs, and when can the compiler remove it?
- In what scenarios is std::variant paired with std::visit preferable to a virtual base-class hierarchy?
Similar questions
- Black-Scholes Implied Volatility Solver, Seed Selection, and Vega
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager