I'm experimenting a bit in C and I'm trying to implement my own Reference Counting System. I've mainly worked with Objective-C in the past but AFAIK autoreleasing objects is something that is unique to Objective-C.
The problem with reference counting is that, when returning objects from methods, there is no correct way to release the object and return it at the same time. If the reference count is 1 releasing it will deallocate the object before it can be returned.
void *testMethod() { return release(object); // Object is already deallocated :'( } Therefore, by autoreleasing an object, it is not deallocated instantly. Instead, when the autorelease pool is drained, all the objects that were autorelease in the scope of the autorelease pool get released.
void *testMethod() { return autorelease(object); } @autorelease { object = retain(testMethod()); } As you can see above, the object gets released when the @autorelease {} block ends, which is after the object has been retained again. This solves the problem.
This solution however can become quite a bottleneck. You have to store every object that gets autoreleased in an array with no predeterminable size, requiring you to realloc a lot of times. Loops that require an autorelease pool have become much slower because of this.
Is there a better solution to this problem?
Or rather, are there any other solutions to this problem at all?