Ref counting for resource classes
Community Forums/Monkey2 Talk/Ref counting for resource classes
| ||
Wouldn't it be a very nice addition if a games oriented language could define some objects to be ref-counted? Couldn't this solve the requirement to Discard images and any other VRAM related resource, as them would be discarded automagically when thei're no longer used? The manual discarding of images can be a source of hard to find bugs, and if a reference counting memory management of this classes can forced somehow, maybe we could make the language easier and safer to use? Just an idea |
| ||
Something like this?Interface IDiscardable Method Discard:Void() End Class RefCounter<T> Private Global objects:Stack<T> Global refs:IntStack Public Function Retain:Void(obj:T) If Not objects Then objects = New Stack<T> If Not refs Then refs = New IntStack Local idx:Int = objects.Find(obj) If idx >= 0 Then refs.Set(idx, refs.Get(idx)+1) End End Function Release:Void(obj:T) If Not objects Or Not refs Then Return Local idx:Int = objects.Find(obj) If idx >= 0 Then Local newVal:Int = refs.Get(idx) - 1 refs.Set(idx, newVal) If newVal <= 0 Then Local disc:IDiscardable = IDiscardable(obj) If disc Then disc.Discard() objects.Remove(obj) End End End End Class Image Implements IDiscardable Method Discard:Void() ' Image's discard stuff End End Disclaimer: I haven't compiled this. |
| ||
mmm well, sort of but automatic. If you need to Retain and Release, then whole purpose of having ref-counting is sort of defeated. |
| ||
Right, but Mojo2 would call Retain/Release itself. It wouldn't be up to the developer. That example just makes it a generic tool so that the developer can use it for other things if they want. |