Interesting boost::shared_ptr constructor

Posted on: 25/12/2009

The future standard extension (some of it is described in the Technical Report on C++ Standard Library Extensions – TR1) is going to include many libraries already contained within boost. One such library is boost’s Smart Pointers.

In this post I would like to show an interesting use-case of the smart_ptr class, through what I consider to be a less commonly known constructor.

One of the constructors offered by boost::shared_ptr is this one:

template <class T> class shared_ptr {
  // Effects: constructs a shared_ptr 
  //          that shares ownership with r and stores p.
  template<class Y> shared_ptr (shared_ptr<Y> const & r, T * p);

Looks like this constructor is not included in std::tr1::shared_ptr implementation, which is pretty curious.

At first glance, the given constructor may seem a little odd; Why would anybody want to create a smart pointer to an object of type T, which shares ownership with an already existing smart pointer to a different type Y ?

But let us consider the following case: Suppose there’s a class, some ResourceContainer, which has a member, Resource. We would like to use the resource regardless of what happens to its container. Invoking the constructor mentioned above, the following is made possible:

#include <boost/shared_ptr.hpp>

struct Resource {};

struct ResourceHandler {
  Resource res_;

int main () {
  boost::shared_ptr<ResourceHandler> rh(new ResourceHandler());
  boost::shared_ptr<Resource> res(rh, &rh->res_);
  return 0;

What we have achieved is pretty useful and elegant: ResourceHandler and its embedded Resource are now tied together — since the reference count is shared, the ResourceHandler object (rh) will not be destructed as long as its Resource (res) is needed. Obviously enough, res itself will never be destructed on its own, as its only a (small) part of ResourceHandler (and as such, will be destructed during the destruction of rh).

You are welcome to think of more use-cases for this construct, as it can be pretty useful in quite a few scenarios.


2 Responses to "Interesting boost::shared_ptr constructor"

Hey man,
Love your posts,
Can you please, Re-Write the last passage?
It’s confusing, you started using ResultHandler , reshndlr , rh , ResourceHandler… and so on.
Unfortunately ResourceHandler and ResultHandler are too similar…


You are absolutely correct. I have slightly edited that paragraph, I hope it makes more sense now.

Thanks for the kind words!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: