Garbage Collection is the term used to describe an algorithm that frees allocated memory when it is no longer in use. There are lots of such algorithms available, each with its advantages and disadvantages. I will present here a method of doing garbage collection that is useful for handling normal game data. Reference CountingThis is not an unknown term, and it's being used in lots of places to handle shared objects with proper release when the object is no longer needed. This is done by attaching a counter to the object, which holds the number of places that hold a pointer to the object. The user code is responsible for calling AddRef() and Release() to increment and decrement the counter. When the counter reaches 0, the object is deleted. Any one who has ever used this method knows that it can be error prone if the AddRef() and Release() functions are not called properly, resulting in either memory leaks or invalid pointers. Later in this article, a way to solve this problem will be presented. To provide the actual reference counting, a base class which handles the counter is created. All this class provides is an addRef() function which increments the counter, a subRef() function which decrements the counter and returns true if the counter is 0.
All objects which we want to include in this allocation scheme, must be instances of a class derived from this base class. It doesn't have to be a direct parent, just an ancestor, so that the object will have the reference counter available. |
|||||||||||