3 ms·
Reference counting solves a number of otherwise difficult problems with the basic memory management of C. Yes, malloc and free are very simple operations, conc
by demallien 16y ago
Reference counting solves a number of otherwise difficult problems with the basic memory management of C. Yes, malloc and free are very simple operations, conceptually, but they are so low level that attempts to create a complex system without putting a layer of memory management over the top are generally destined to fail. Note that if you want, reference counting can be reduced to malloc/free - you simply use alloc/release instead of malloc/free - it's a direct substitution. But reference counting helps you for use cases that are more difficult.
Here's a real life example that I ran into a few years ago when trying to write a largish system using just malloc and free. It was in the world of Conditional Access, and I was doing a cardless system that used a secure tunnel to talk to a server. I had an object that represented the Service Operator, and this object created the secure tunnel to talk with the server representing the service operator at the head-end. It worked just fine most of the time until I tried to handle the case of the command that deleted the representation of the Service Operator in my set top box. When I called Delete on the Service Operator object, my secure tunnel blew up, because it relied on information that was held by the Service Operator object. What I needed was a way of being able to say Delete the Service Operator object, but wait until the tunnel has closed before doing it.
Now, you could just set a special flag in the tunnel object saying "delete the service operator after closing", or you could create a Service Operator callback that is called when the tunnel closes, and it doesn't act on any request to delete until that callback is received - but then what happens if someone other than the tunnel wants to delete the service operator? The callback never comes. It was a version of this system that I used in the end, but it was far more complicated than it would have been with reference counting. The solution when using reference counting is simply to a retain of the ServiceOperator when the tunnel opens, do a release when the tunnel closes, and if the tunnel really wants to delete the service operator, it does a release in mid-communication. As simple as can be.
- blub 16y agoThanks. Obj-C is better at sharing objects then. What if I create a custom malloc/free that keeps a share count at the beginning of the memory block, would that be similar?