Reference Counting

Reference counting is a way of tracking the number of owners of a resource with shared ownership. The resource has a count associated with it; typically this count will start at 1, representing the allocator of the resource. When the object representing the source is copied, the reference count is increased; when one of the copies is destructed, the count will be decremented. When the last object is destructed, the count will be 0, and the object is released.

Reference counting is often used by smart pointer implementations.

Reference counting implementations
The simplest form of reference counting uses two classes, which we'll call R (the resource) and R_ref (a reference).

struct R { R : refs(1) { rid = allocate_R; }  ~R { deallocate_R(rid); }  int rid; /* opaque resource id */ int refs; /* number of references */ }; struct R_ref { R *r; /* resource */ R_ref { r = new R; // start with refcount of 1 }  ~R_ref { if (--r->refs == 0) // we are the last R_ref being destroyed delete r;  } R_ref(R_ref const &other) { // the resource is being copied, so we need to increase the refcount r = other.r;    ++r->refs; }  R_ref &operator= (R_ref const &other) { // assignment should release the resource we hold... if (--r->refs == 0) delete r;    // ...and increment the reference count of the new resource r = other.r;    ++r->refs; return *this; } };

When a module wishes to allocate a new resource, it creates an R_ref object (generally on the stack, not the heap). It can then copy R_refs and pass them to other modules; only when no modules have any R_ref objects will the resource be freed.

Note that this example does not discuss exception safety, which can impose some additional complexity on the implementation.