boost::weak_ptr

As a good introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Sometimes it is useful to have a way to keep an eye on a resource without actually claiming for its ownership. That is actually the point of weak_ptr. It is a duty of the related shared_ptr to set to null the pointer in weak_ptr when it is ready to release it.

What we have to do, is checking the weak_ptr validity, through its method expired(). Then, if we actually want to use the resource, we could create a shared_ptr from the weak_ptr.

Here is a short example:

#include "boost/shared_ptr.hpp"
#include "boost/weak_ptr.hpp"
#include <iostream>

using std::cout;
using std::endl;
using boost::shared_ptr;
using boost::weak_ptr;
using boost::bad_weak_ptr;

namespace
{
class A
{
public:
void hello() { cout << "Hello from A" << endl; }
};
}

void weakPtr()
{
weak_ptr<A> w;
if(w.expired())
cout << "No associated shared_ptr" << endl;

{
shared_ptr<A> p(new A());
p->hello();

w = p;
// w->hello(); // we can't do that!

cout << "A weak_ptr do not increase the reference count: " << p.use_count() << endl;

// Create a shared_ptr from the weak_ptr
shared_ptr<A> p2(w);
cout << "Now the reference count is " << p.use_count() << endl;
}


if(w.expired())
cout << "The shared_ptr is expired" << endl;

cout << "If we create a new shared_ptr using lock() ..." << endl;
shared_ptr<A> p3 = w.lock();

if(!p3)
cout << "... we should check it is valid before using it" << endl;

try
{
cout << "If we create a new shared_ptr passing the weak_ptr to its ctor ..." << endl;
shared_ptr<A> p3(w);
}
catch(const bad_weak_ptr& bwp)
{
cout << "... it could throw a " << bwp.what() << " exception" << endl;
}
}

No comments:

Post a Comment