Interesting boost::shared_ptr constructor

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 thoughts on “Interesting boost::shared_ptr constructor

  1. 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…

    Thanks!

    1. 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

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>