mario::konrad
programming / C++ / sailing / nerd stuff
Lightweight Shared and Weak Pointer
© 2006 / Mario Konrad

Introduction

Handling memory manually raises quickly to more are burden then a feature, especially in middle and large software projects.

Many programmers appreciate the luxury of not having to handle the deallocation of resources.

Every C++ Programmer should know (at least by name) the boost library by now. If you like to know how shared and weak pointer may be implemented, or you like to use a lightweight version of them, this tutorial/demo may interest you.

With the finalization of C++11, this tutorial has only educational purposes.

Demo

In the chapter Download, you’ll find a demonstration of both, shared pointer as well as weak pointers.

To give an impression, here a rather short demo:

class Foo
{
  public:
    Foo() { std::cout << __FUNCTION__ << "\n"; }
    ~Foo() { std::cout << __FUNCTION__ << "\n"; }
};

void test1(void)
{
  typedef mem::shared_ptr`<Foo>` FooShPtr;
  typedef mem::weak_ptr`<Foo>` FooWkPtr;

  // create the only Foo object, constructor is called.
  FooShPtr f = FooShPtr(new Foo);

  std::cout << "ref count = " << f.ref_count() << "\n";

  // create weak pointer ("observer") from the shared pointer.
  FooWkPtr wk_f(f);

  std::cout << "valid : " << wk_f.valid() << "\n";

  // reset the object, invalidates the weak pointer, also the destructor
  // of Foo is called.
  f.reset();

  std::cout << "valid : " << wk_f.valid() << "\n";
}

It also works with the standard library:

void test2(void)
{
  // define types
  typedef mem::shared_ptr`<Foo>` FooShPtr;
  typedef std::vector`<FooShPtr>` FooShPtrVec;

  // the vector itself
  FooShPtrVec vec;

  // fill it up
  vec.push_back(FooShPtr(new Foo));
  vec.push_back(FooShPtr(new Foo));
  vec.push_back(FooShPtr(new Foo));

  // vector _and_ Foo objects are released automatically
}

Download

All source files provided by this page are free to modify, distribute or to use them in any kind you like. Use them on your own risk.