Counting references to objects
In reference counting, each object keeps a count of how many pointers refer to it. This number starts out as 1
when an object is first allocated and a reference to it is provided to a surrounding expression. The reference count is incremented when the reference is stored in a variable, including when it is passed as a parameter or stored in a data structure. The count is decremented whenever a reference is overwritten by assigning a variable to refer elsewhere, or when a reference no longer exists (such as when a local variable ceases to exist because a function returns). If the reference count reaches 0
, the memory for that object is garbage because nothing points to it. At that point, the memory can be reused for another purpose. This all seems reasonable; look at what it would take to add reference counting to our example language in this book, Jzero.
Adding reference counting to Jzero
Jzero allocates two kinds of things from the heap that...