C++ Implementation Details: Containers and Polymorphism
Data Structure DesignModel answerLast updated
Explain the internal mechanics of std::vector growth, std::unordered_map collision handling, and virtual function dispatch in C++.
Describe the following C++ implementation details:
-
std::vector::push_backcomplexity and memory management:- What are the amortized and worst-case time complexities?
- How does capacity expansion work (growth strategy, reallocation process)?
- What happens to iterators and references during reallocation?
- How do move semantics affect the reallocation process?
-
std::unordered_mapinternal structure:- How are elements stored and organized internally?
- How are hash collisions resolved?
- What triggers a rehash, and what happens during one?
- What are the complexity guarantees for common operations?
- What gets invalidated when elements are inserted or removed?
-
Virtual functions and runtime polymorphism:
- What problem do virtual functions solve?
- How is dynamic dispatch implemented at the machine level?
- What are the runtime and memory overheads?
- When must destructors be virtual, and why?
- What are the trade-offs compared to compile-time alternatives?
Hints
Hint 1
For vector growth, think about why geometric expansion is necessary for amortized constant time.
Hint 2
Consider how unordered_map must preserve references even when the table is restructured.
Hint 3
Virtual dispatch requires runtime lookups—what data structure makes this possible?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: C++ Container and Polymorphism Internals
A strong answer demonstrates understanding of what the compiler and runtime actually do, not just the public API. Present guarantees first, then implementation mechanics, then practical implications.
1. std::vector::push_back: Complexity and Growth Strategy
Time Complexity
Amortized O(1), but worst-case O(n) for a single operation when reallocation occurs.
Growth Mechanism
When size() == capacity(), the vector must allocate a larger buffer. Standard implementations use geometric growth:
- GCC/Clang: multiply capacity by 2
- MSVC: multiply by 1.5
Why geometric growth gives amortized O(1): With growth factor k > 1, inserting n elements requires moving elements across log_k(n) reallocations. Total moves: n(1 + 1/k + 1/k² + ...) = n × k/(k-1), which is O(n) total work, hence O(1) per insertion.
Constant-size growth (e.g., +100 each time) would require O(n²) total work—unacceptable.
Why 1.5 vs 2.0 matters: A factor below φ ≈ 1.618 (golden ratio) allows the allocator to potentially reuse previously freed memory blocks. Factor 2 never permits this because each new block is larger than all previous blocks combined.
Reallocation Steps
- Allocate new buffer with increased capacity
- Construct the new element first at the new buffer's
size()position (handles self-reference cases likev.push_back(v[0])) - Transfer existing elements using move-if-noexcept semantics:
- If move constructor is
noexcept, elements are moved - Otherwise, elements are copied to maintain strong exception safety
- If move constructor is
- Destroy old elements and deallocate old buffer
Critical detail: Non-noexcept move constructors force copying during reallocation. Always mark move constructors noexcept when possible.
Invalidation Rules
- Reallocation occurs: All iterators, pointers, and references are invalidated
- No reallocation: Only the
end()iterator is invalidated
Best practices: Use reserve(n) to pre-allocate capacity and eliminate reallocation from performance-critical paths. Use emplace_back to construct in-place and avoid temporary objects.
2. std::unordered_map: Hash Table Implementation
Internal Organization
Uses separate chaining (linked lists) for collision resolution. The standard effectively mandates this through two requirements:
- Element references must remain valid across rehashing
- The bucket interface (
bucket(), bucket iterators) must be exposed
Both requirements imply node-based storage where elements live in individually allocated nodes.
Memory Layout
Typical implementation (e.g., libstdc++):
- Single singly-linked list connecting all nodes
- Bucket array where each entry points to the node before the first element in that bucket (enables O(1) erasure)
- Each node contains the key-value pair, next pointer, and often a cached hash value
- Hash computation:
bucket_index = hash(key) % bucket_countor& (bucket_count - 1)for power-of-two sizes
Collision Handling
When multiple keys hash to the same bucket, they form a chain. Lookup walks the chain comparing keys with KeyEqual. This makes worst-case complexity O(n) when all elements collide into one bucket (adversarial or pathological hash function).
Important: std::hash<int> is often the identity function—keys that are multiples of the bucket count will collide.
Load Factor and Rehashing
- Load factor =
size() / bucket_count() - Default
max_load_factor()is 1.0 - When insertion would exceed this threshold, the table rehashes: allocates a larger bucket array (typically ~2× the size), recomputes bucket indices, and relinks all nodes
Key property: Nodes are never moved or reallocated during rehash—only the bucket array changes. This is why element references stay valid.
Complexity Guarantees
| Operation | Average | Worst Case |
|---|---|---|
find | O(1) | O(n) |
insert | O(1) amortized | O(n) |
erase | O(1) | O(n) |
Invalidation Rules
- Rehash: Invalidates iterators but preserves all pointers and references to elements
- Insert (no rehash): Nothing invalidated
- Erase: Only invalidates iterators and references to the erased element
Performance Considerations
- Cache-unfriendly: Pointer chasing through linked nodes defeats CPU cache
- Memory overhead: One allocation per element plus pointer storage
- Alternatives for low-latency code: Open-addressing tables (e.g.,
absl::flat_hash_map, Robin Hood hashing) provide contiguous memory and better cache behavior, trading away reference stability - Mitigations: Call
reserve(n)upfront, use stronger hash functions, consider custom allocators
3. Virtual Functions and Dynamic Dispatch
Purpose
Enable runtime polymorphism: the correct function is chosen based on the object's actual (dynamic) type, not the static type of the pointer or reference used to call it.
Implementation Mechanism
Uses vtables (virtual function tables) and vptrs (virtual pointers):
-
Each polymorphic class has one vtable in read-only memory containing:
- Function pointers for each virtual method
- RTTI (Run-Time Type Information)
- Offset-to-top metadata for multiple inheritance
-
Each object contains a hidden vptr (typically the first 8 bytes) pointing to its class's vtable
Call sequence for ptr->method():
// Conceptual translation
vtable_ptr = *(void**)ptr; // load vptr from object
function_ptr = vtable_ptr[method_slot]; // index into vtable
function_ptr(ptr); // indirect call through function pointer
Constructor/destructor behavior: The vptr is updated as each level of the inheritance hierarchy constructs/destructs. This is why virtual calls inside constructors dispatch to the current class's version, not derived overrides.
Runtime and Memory Costs
Memory:
- One vptr per object (8 bytes on 64-bit systems)
- One vtable per class definition
- Can significantly impact small objects' cache efficiency
Runtime:
- Two dependent memory loads followed by an indirect branch
- Branch misprediction penalty: 15–20 cycles when the target cannot be predicted
- Lost inlining opportunities: The main cost—prevents constant propagation, dead code elimination, auto-vectorization, and other optimizations
- Devirtualization: Compilers can optimize away virtual calls when the type is statically known; marking classes/methods
finaland using Link-Time Optimization helps
Virtual Destructors
Rule: If a class may be deleted through a base pointer, the base destructor must be virtual.
struct Base { virtual ~Base() = default; };
struct Derived : Base { std::vector<int> data; };
Base* ptr = new Derived();
delete ptr; // OK: calls Derived's destructor, then Base's
Without a virtual destructor, delete ptr invokes undefined behavior—in practice, Derived's members leak and destructors don't run.
Guideline: Base class destructors should be either:
- Public and virtual (polymorphic base), or
- Protected and non-virtual (prevents polymorphic deletion)
Alternatives and Trade-offs
Templates (static polymorphism):
- Zero runtime overhead
- Complete inlining
- Code bloat (one instantiation per type)
- No heterogeneous collections
- All types known at compile time
std::variant + std::visit:
- Type-safe discriminated union
- No heap allocation or indirection
- Fixed set of types
- Branch-based dispatch (typically faster than vtable when hot)
Type erasure patterns:
- Hides implementation behind value semantics
- Combines vtable-style dispatch with move/copy semantics
- Examples:
std::function,std::any
When to use virtual functions:
- Need runtime polymorphism with heterogeneous collections
- Plugin architectures, extensibility points
- Performance cost is acceptable for the design flexibility gained
Common Mistakes
- Forgetting
reserve()before bulk insertions into vector - Not marking move constructors
noexcept, forcing copies - Using
std::hash<int>with clustered integer keys (identity hash creates collisions) - Missing virtual destructors in polymorphic base classes
- Assuming
unordered_mapis always faster thanmap(not true for small sizes or poor hash functions) - Virtual calls in tight loops without considering devirtualization or alternatives