Using Boost to manage smart pointers
Feb.09, 2008 in
c++
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 }

Leave a Reply