/wiːk ˈrɛfərəns/

noun … “Reference that doesn’t prevent object deallocation.”

Weak Reference is a type of pointer or reference to an object that does not increase the object’s reference count in reference counting memory management systems. This allows the referenced object to be garbage-collected when no strong references exist, preventing memory leaks caused by circular references. Weak references are commonly used in caching, observer patterns, and resource management where optional access is needed without affecting the object’s lifetime.

Key characteristics of Weak Reference include:

  • Non-owning reference: does not contribute to the reference count of the object.
  • Automatic nullification: becomes null or invalid when the object is garbage-collected.
  • Cyclic reference mitigation: helps break reference cycles that would prevent deallocation.
  • Use in caches: allows temporary objects to be cached without forcing them to persist.
  • Integration with garbage-collected languages: supported in Python, Java, .NET, and others.

Workflow example: Using weak references in Python:

import weakref
class Node { pass }

node = Node()
weak_node_ref = weakref.ref(node)
print(weak_node_ref())      -- Returns Node instance

node = None                 -- Node deallocated
print(weak_node_ref())      -- Returns None

Here, weak_node_ref allows access to node while it exists but does not prevent its deallocation when the strong reference is removed.

Conceptually, Weak Reference is like a sticky note on a book: it reminds you of the book’s existence but doesn’t keep the book from being removed from the shelf.

See Reference Counting, Garbage Collection, Pointer, Cache, Circular Reference.