Wazoo Enterprises

Having fun in game development!


Using Boost to manage smart pointers

I’m sure the concept of a “smart” pointer was born from the frustration and tedium of tracking base object pointers in the C++ language. In a nutshell, smart pointers are pointers to dynamically allocated objects on the heap. They’re used identical to a “normal” pointer, however they properly delete the object they are pointing to when necessary. If your program triggers an exception, then a smart pointer will properly deallocate the used the memory on the heap. The shared_ptr object in the Boost C++ library internally uses a reference counting system in a non-intrusive fashion. In other words, the object will auto-update itself whenever its reference count needs to be updated, so that you don’t have to!

#include 

//create a base object for whatever..
class IBaseObject
{
  public:
    IBaseObject(){}
   virtual ~IBaseObject(){}
  //snip!
};

int main(int argc, char* argv[])
{
  // create a new IBaseObject instance with one reference
  boost::shared_ptr objA(new IBaseObject); 

  printf(”Ding! %i reference!\n”, objA.use_count()); // 1

  // assign a second pointer to it:
  boost::shared_ptr objB = objA; // should be 2 refs by now

  printf(”Ding! %i references\n”, objB.use_count()); // 2

  objA.reset(); //set the first pointer to NULL
  printf(”Ding! %i references\n”, objB.use_count());  // 1

  // the reference count will drop to zero
  // when objB goes out of scope

}

Using Boost for managing a list of pointers

One of the popular uses of the Standard Template Library (STL) in the C++ language is to manage a dynamic list of pointers. For example, if you have a rendering system for your game which works with a common base object that every drawable object is derived from.

If you were using STL, then typically you would create something like the following:

#include <iostream>
#include <list>

using namespace std;

class IRenderObj
{
public:
float x;
float y;
float z;
};

main()
{
list<IRenderObj*> drawList;
list<IRenderObj*>::iterator drawListIter;

IRenderObj *a= new IRenderObj;
IRenderObj *b= new IRenderObj;
IRenderObj *c= new IRenderObj;

a->x = 0.0f; a->y = 0.0f; a->z = 0.0f;
b->x = 0.0f; b->y = 1.0f; b->z = 0.0f;
c->x = 1.0f; c->y = 0.0f; c->z = -10.0f;

drawList.push_back(a);
drawList.push_back(b);
drawList.push_back(c);

for (drawListIter = drawList.begin();
drawListIter != drawList.end();
drawListIter++)
{
//draw, translate each vector
glTranslatef( (*drawListIter)->x, (*drawListIter)->y, (*drawListIter)->z );

}

// Now Free pointers
for (drawListIter = drawList.begin();
drawListIter != drawList.end();
drawListIter++)
{
delete *drawListIter;
}

drawList.clear(); // List is deleted.

}

Continue Reading →