9.4 Objects, VTables, Closures, and Captured Variables
Runtime behavior for object dispatch and closures is where static structure meets dynamic state.
For objects, compilers often implement dynamic dispatch with virtual tables (vtables): a stable slot protocol resolved at runtime through object metadata.
For closures, compilers must preserve values or references across scope boundaries, often by generating environment objects.
Both mechanisms are fundamentally about preserving late-bound behavior safely and efficiently.
VTable Slot Stability
When a derived class overrides a method, it usually reuses the same slot index as the base declaration. That preserves polymorphic call-site behavior.
Adding a new virtual method generally appends slots instead of reindexing existing ones. Reindexing would break ABI compatibility and dispatch expectations.
This slot discipline is why "same call-site, different dynamic target" works predictably.
Closure Capture Semantics
Closures raise a lifetime question: what happens when captured variables outlive the defining stack frame?
Compilers commonly choose among:
- capture by value (snapshot semantics)
- capture by reference/shared environment (live-view semantics)
- hybrid strategies per language rule
Each choice changes visible behavior under mutation.
Escaping Variables and Environment Lowering
If captured variables escape, stack allocation alone becomes invalid. The compiler must lift storage to heap-backed environments or equivalent runtime structures.
That transform must preserve:
- lifetime safety
- aliasing semantics
- mutation visibility rules
Failure here creates subtle bugs that pass type checking but fail at runtime.