Reference Counting
Subject: Computer and Technology noun /ˈrɛf.ər.əns ˌkaʊn.tɪŋ/ 1 definition
- memory-management
- garbage-collection
- resource-management
- programming-languages
-
Definition (noun)
Entry #256 · UpdatedReference Counting is an automatic memory and resource management technique in which each shared object or resource maintains an integer counter of the active references pointing to it. The counter increments whenever a reference is created or copied and decrements when a reference is overwritten or destroyed, immediately reclaiming the resource once the count drops to zero. Unlike tracing garbage collection, this mechanism delivers deterministic, incremental deallocation without full-heap pauses, though naive implementations cannot reclaim cyclic reference graphs without weak references or an auxiliary cycle detector.
Common Forms
Immediate Reference Counting: Updates the counter synchronously on every reference creation or destruction and immediately reclaims the resource when the count hits zero, providing deterministic cleanup (such as in Rust's
Rc<T>or Swift ARC).Atomic Reference Counting: Synchronizes counter updates using atomic CPU instructions so shared ownership stays thread-safe across concurrent threads without external locks, powering C++
std::shared_ptrand Rust'sArc<T>.Deferred Reference Counting: Skips counter updates for short-lived stack and register references, instead recording objects with zero heap references in a zero-count table that is reconciled during periodic root scans.
Hybrid Reference Counting: Combines reference counting with weak references or a periodic tracing cycle collector, such as CPython's
gcmodule, to identify and reclaim unreachable reference cycles.
Example
When a C++ media server loads a 4 MB video frame into a
std::shared_ptr, its control block initializes the reference count to1and increments it to3as two streaming workers copy the handle. As the loader and both workers finish and release their handles, the counter atomically decrements back to0, immediately freeing the 4 MB frame without a garbage collection pause.