# How are weak references in a reference counted system implemented?

When reference counting is used for automatic memory management (e.g. Objective C or Swift), it is well know that “loops” give problems. E.g.

class Car
{
Engine engine;
}
class Engine
{
Car installedIn;
}


Swift (along with other systems) avoids this problem by allowing the reference from the car instance to the engine instance to be weak. So that the engine instance does not keep the car instance alive, and when the car instance is freed, then the reference from the engine instance is set to null.

What are the standard ways of implementing this within a runtime/compiler?

• The short answer is that in a reference-counted system weak references are simply not counted. Which is actually a simpler/base/primitive case of "normal" assignment. Normally in a reference-counted environment the runtime/compiler has to inject instructions to increment the reference-count for a given object every time a new pointer to it is assigned (and to decrement the count when the pointer goes out of scope). With a weak reference, those extra instructions can simply be omitted. – aroth Sep 15 '15 at 4:23
• @aroth, that is the easy bit, the hard bit is that NULL (not a reference to a freed object) is returned when the week reference is accessed. – Ian Ringrose Sep 15 '15 at 18:40
• Yes. You'll need someone with detailed internal knowledge of the compiler/runtime to answer that part. All I can do is speculate. For instance, perhaps the runtime maintains a map (or similar structure) that associates the address of each allocated object with the addresses of all the in-scope pointers that refer to it, and when an object's reference count reaches 0 it's removed from the map and any remaining in-scope pointers are set to nil. That might work, but no idea if that's akin to what it actually does. – aroth Sep 15 '15 at 23:33