Reputation:
I am making an interpreter in C, and I'm having a problem with my reference counting.
Each value
(which is the interpreter's representation... of a value) is allocated with refcount
0. Once it gets added to the stack, it increments the refcount
.
The only way to get a value
off the stack is to pop it off it, but that leads to problems. My popping function returns the value
that is popped, but if the refcount
is 0 and I destroy the value I can no longer return it.
I get that I should probably put the refcount
check somewhere else, but that just seems ugly as there are a lot of places that use the popping function.
What can I do to workaround this issue? Is implementing a real GC algorithm necessary in this case?
Upvotes: 0
Views: 143
Reputation: 19504
As a general rule, increment the count when creating a reference and decrement when deleting a reference. But there's also a third type of transaction (or an optimized composition of the two) where there's just a transfer and you don't change the count at all.
This is the case if you pop the value from the stack and them proceed to use the value (in a local variable, maybe). First the object was on the stack, and now its in a variable; but there's still only one object. The reference count doesn't change until you're done with it and ready to discard the reference.
Upvotes: 0
Reputation: 649
whenever you create object or value in your case, you should set the refcount to 1. On pushing to the stack, increment it. On poping, decrement. On pop each operation decrement and check th refcount, destroy value if refcount is zero. Which function destoy-value already be doing so you just need to call that function on pop.
Upvotes: 0
Reputation: 1274
I use my own data base system which also uses a kind of refcount.
When an object is stored into a data base, then its refcount is incremented. When I get an object from a data base, its refcount remains unchanged. It is decremented only if the object is deleted by any way (usually the deletion of a data base containing it or its replacement by another object in a data base containing it). The object is really destroyed only when its refcount is equal to zero AND its deletion is required.
Upvotes: 1