Course contentsShow
← Computer Science
Lesson 2105 of 2,87247. Memory Management in LanguagesFree lesson

Reference Count Operations

Learning increment and decrement operations that occur during assignment, function calls, and scope exit.

Reference Count Operations

You'll learn how reference counts are updated during assignment, function calls, and scope exit.

How Reference Counts Change

Reference counting tracks how many references point to an object. But when do these counts actually change? Three common operations trigger updates:

Assignment Operations

When you assign a reference, two things happen:

  • Increment: The new target's count goes up (you just added a pointer to it)
  • Decrement: The old target's count goes down (you removed a pointer from it)
ptr1 = objA  // objA.refCount++
ptr1 = objB  // objB.refCount++, objA.refCount--

Think of it like changing where your bookmark points in different books—you're now tracking one book and no longer tracking the other.

Function Calls

When passing objects to functions:

  • On entry: Increment the count (the parameter now references it)
  • On return: Decrement the count (the parameter goes out of scope)
function process(obj) {  // obj.refCount++ on entry
    // use obj
}  // obj.refCount-- on exit

Scope Exit

When a variable leaves scope (end of block, function return), decrement the count of whatever it pointed to. If the count reaches zero, the object can be freed immediately.

{
    ptr = objC  // objC.refCount++
}  // scope ends: objC.refCount--

The Cascade Effect

Here's the critical detail: when an object's count hits zero and gets freed, you must decrement the counts of all objects it references. This can trigger a cascade of deallocations.

Key Takeaway: Reference count operations—increment on assignment/parameter passing, decrement on reassignment/scope exit—maintain accurate lifetime tracking, with zero counts triggering immediate deallocation.