Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
87 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:


 Reference Counting
 Smart Pointers
 Reference counting
 and STL


 Get the Source
 Printable version


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 Counting

This 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.

class RefCntObject { public: virtual ~RefCntObject() {} /** Default constructor. Initial reference count is 0, and will be incremented as soon as the object is pointed to. */ RefCntObject() : m_refcnt(0) {} /** Add 1 to the reference count. */ void addRef() { m_refcnt++; } /** Subtract 1 from the reference count. Returns true if the reference count has reached 0 and the object should be deleted. */ bool subRef() { return (--m_refcnt <= 0); } private: int m_refcnt; };

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.

Next : Smart Pointers