Arrays, shared_ptr< T >s, and deleters

In my last few posts about shared_ptr<T>s I’ve been using a struct called private_deleter. When you first attach a target object to a shared_ptr<T> you can also specify a deleter, which is a functor with an operator() that takes a single argument, a pointer to the target object, and deletes it.

  // Instances of some_type will be managed
  // with shared_ptr< some_type >s.
  { };

  // Deleter that works when you create
  // some_type with operator new.
  {   void
    operator ()( some_type * p)
      { delete p; }

  // This shared_ptr has no deleter, so the
  // target is deleted with the function
  // boost::checked_delete< some_type >(..).
  shared_ptr< some_type >
  new some_type);

  // Boost provides a standard deleter struct
  // that calls boost::checked_delete<T>(..).
  shared_ptr< some_type >
  new some_type,
  boost::checked_deleter< some_type >( ));

  // This target object is bound to a new instance
  // of our deleter struct, defined above.
  shared_ptr< some_type >
  new some_type,
  some_type_deleter( ));

You use the deleter, of course, to control target object deletion. Which is symmetric since you also control target creation. Without the deleter you could only create target objects with operator new to match the operator delete assumed by shared_ptr.

Since the deleter becomes part of the intermediate object (aka the “control block”), you can also use it as a way to add variables and functions without intruding on the target class. For example, you can use it to store a list of notifier functors to be triggered when the target is deleted. Or you can use it as a chunk of memory in which you construct the target object. But in this post we’re just going to use the deleter to delete.

The Boost smart pointers provide a shared pointer just for arrays, called shared_array<T>. It is similar to shared_ptr<T> except it uses operator delete[] instead of operator delete to delete the target. But shared_array<T> is not part of TR1, and it is not necessary since shared_ptr<T> supports custom deleters.

The following shows how to use a deleter so shared_ptr<T> correctly deletes arrays.

# include <boost/detail/lightweight_test.hpp>
# include <boost/shared_ptr.hpp>
using boost::shared_ptr;

  // Deleter to correctly delete arrays
  // (remember it's OK to delete a const)
  template< typename T >
    operator ()( T const * p)
      { delete[] p; }

  // Example target object
  { my_type( )  { balance += 1; }
    ~my_type( ) { balance -= 1; }
    static int balance;
  int my_type::balance = 0;

main( )
  // Create an array and bind it to an array_deleter
  // with shared_ptr. The my_type constructor is
  // called 7 times, followed by 7 calls to the
  // destructor.
  {    shared_ptr< my_type >
      new my_type[ 7 ],
      array_deleter< my_type >( ));
  BOOST_TEST( 0 == my_type::balance);

  return boost::report_errors( );

Boost even provides an array-deleter class (checked_array_deleter<T>) so you don’t have to define one yourself.

# include <boost/shared_ptr.hpp>
using boost::shared_ptr;
using boost::checked_array_deleter;

  shared_ptr< my_type >
  new my_type[ 53 ],
  checked_array_deleter< my_type >( ));

Since shared_array<T> is no longer necessary to support array deletion, I suspect it will never become part of the standard library. operator [] is not enough justification for its existence. It will languish in the Boost library, a barely supported dead-end experiment, and will never be integrated with shared_ptr and weak_ptr.

As a final note, another way to work with arrays and shared_ptrs is to use an array wrapper like the TR1 array class. Since you can allocate these objects with operator new you can rely on the default shared_ptr deleter.

# include <boost/array.hpp>
using boost::array;

  shared_ptr< array< my_type, 4 > >
  new array< my_type, 4 >);

But shared_ptr< array< my_type, 4 > > is a lot more awkward than simple shared_ptr< my_type >, and I doubt it will become a common idiom.


38 Responses to “Arrays, shared_ptr< T >s, and deleters”

  1. SpaƟ mit stl::shared_ptr auf ein c-array in C++ (Memory Tester) « Wissenswertes on January 24th, 2011 8:30 am

    […] Mehr Spannendes zum Thema shared_ptr und Arrays findet sich hier: shared_ptr bei MSDN Arrays, shared_ptr and deleters shared_ptr und c-Arrays shared_ptr Tutorial Diskussion auf Stackoverflow Wer mit dem Code […]

  2. on July 4th, 2012 12:10 pm

    senior living can be costly if you have not found a very first-class business or that
    offers a great deal,

  3. ourmidland url on July 7th, 2012 8:52 am

    Im no professional, conversely I feel you just crafted a very fine
    point point. You naturally understand what youre talking about, and I
    can seriously determine behind that. Thanks for staying so upfront and so truthful.

  4. scholarships for single mothers on July 8th, 2012 3:35 am

    Thank you pertaining to discussing that superb content
    material on your web site. I ran into it on that the search
    engines. I am going to check to come back after you publish extra aricles.

  5. scholarships for college students|scholarships for college students in texas|2011 scholarships for college students|scholarships for college students in california|scholarships for college students 2011|easy scholarships for college students|grants and sf on July 8th, 2012 2:08 pm

    The script, cowritten by McKay & Chris Henchy, sends
    up buddy cop movies with more verve than most films of this type.

  6. business grants for single mothers on July 8th, 2012 3:27 pm

    i am seeking for gadget reviews this december coz i wanna buy
    some of the latest gadgets for my girlfriend

  7. money assistance for single mothers on July 8th, 2012 4:08 pm

    I have been exploring for a bit for any highquality
    articles or weblog posts in this kind of area . Exploring in Yahoo I eventually stumbled upon this website.
    Studying this information So im satisfied to exhibit that Ive an
    incredibly just right uncanny feeling I found out exactly what I needed.
    I most indubitably will make certain to dont fail to
    remember this website and provides it a look a continuing.

  8. cell phone lookup on July 8th, 2012 4:43 pm

    A lot of thanks for this kind of facts I had been hunting all Lookup engines to discover it!

  9. government scholarships for single mothers on July 8th, 2012 4:55 pm

    soem internet sites that provide download games have viruses and spywares on it.
    so make sure to have some antivirus on your PC,,

  10. cell phone lookup on July 10th, 2012 4:17 am

    This is so great that I had to comment. Im typically just a lurker, taking in knowledge and nodding my head in quiet approval at the first-rate stuff.

    this required written props. Theory rocksthanks.

  11. reverse cell phone lookup white pages on July 10th, 2012 4:22 am

    Recently, I didnt provide lots of consideration to making comments on site page articles and have placed comments even much less.

    Reading via your enjoyable post, will help me to do so sometimes.

  12. on July 16th, 2012 12:40 pm

    Undeniably believe that which you stated. Your favorite reason seemed to be via internet the
    simplest thing to be aware of. I say to you, I certainly figure out annoyed while people think about
    worries they just dont be acquainted with about. You managed to hit that the nail upon that the
    top as well because defined out the whole thing without
    having side effect , people can take a signal.
    Will likely be back to find more. Thanks

  13. on July 16th, 2012 12:58 pm

    Write more, thats all I have to say. Literally, it seems as though you relied on the
    video to make your point. You definitely know what youre talking about, why waste your intelligence on just posting videos to your site when
    you could be giving us something informative to

  14. on July 16th, 2012 2:01 pm

    When visiting internet sites, i always look for a very
    nice content for example yours ,

  15. on July 16th, 2012 2:22 pm

    very fine post, i definitely adore this amazing site, persist
    with it

  16. criminal background check on July 16th, 2012 3:11 pm

    i would always be a fan of Nip/Tuck, i was saddened about that the
    episode when one of the doctors got breast cancer

  17. on July 16th, 2012 3:23 pm

    Hmm is anyone else experiencing problems with the pictures on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  18. reverse phone lookup on July 16th, 2012 4:50 pm

    When visiting web pages, i always look for a very
    nice content like yours ,

  19. phone number lookup on July 16th, 2012 5:52 pm

    Thank you, Ive recently been searching for info about this subject for ages and yours is that the best I have located so far.

  20. on July 16th, 2012 8:15 pm

    I don’t even know how I ended up here, but I thought this post was good. I do not know who you are but certainly you are going to a famous blogger if you aren’t already ;) Cheers!

  21. on July 16th, 2012 8:17 pm

    An impressive share, I simply given this onto
    a colleague who was carrying out a minor analysis on this.
    And hubby the truth is bought me breakfast because I ran across it for him.
    smile. So i would along the lines of to reword that Thnx with the treat!
    But yeah Thnkx for spending time to talk about this, I feel strongly
    regarding this and love reading read more about this topic.
    When doable, as you become expertise, does one
    mind updating your blog with a ton more details It truly
    is highly of great help for me. Big thumb up due to this article!

  22. reverse address lookup on July 16th, 2012 8:48 pm

    Thank you for this specific facts I was basically looking
    all Bing to uncover it!

  23. reverse cell phone lookup on July 16th, 2012 10:21 pm

    You can certainly see your skills within the work you write.
    The sector hopes for more passionate writers such as you
    who aren’t afraid to mention how they believe. All the time go after your heart.

  24. reverse phone on July 17th, 2012 2:03 am

    I cant believe the quantity of spam that your
    website is getting hit with. When you will need any other assist
    with deleting that the spam comments please email me.

  25. on July 17th, 2012 2:30 am

    Pretty element of content. I just stumbled upon your
    weblog and in accession capital to assert that I determine really
    enjoyed account your weblog posts. Anyway I
    will be subscribing to your feeds or even I
    achievement you figure out admission to consistently promptly.

  26. on July 17th, 2012 2:34 am

    Universial Studios offers one of the best studio in Hollywood,
    they also make great films

  27. on July 17th, 2012 2:36 am

    I am often to blogging we actually appreciate your posts.
    The content has truly peaks my interest.
    I am going to bookmark your web site and maintain checking possible data.

  28. reverse phone lookup on July 18th, 2012 1:38 am

    By how you compose, an person appear to be an expert author.

  29. on July 25th, 2012 1:56 am

    dress shops that present discounts are very wide-ranging in our
    place and i always shop at them

  30. how to make money online on July 27th, 2012 6:30 am

    I am curious to lookup out out what blog line of attack
    youre through that the use of Im experiencing some minor
    security problems with my latest blog and I would
    such as to find something more riskfree. Do you have any recommendations

  31. on July 29th, 2012 9:10 am

    This is really serious, Youre an incredibly efficient writer.
    I have joined with your feed and also will enjoy
    finding your incredible writeups. In addition, I have shared your blog
    post with our social networking web pages.

  32. Shelton on July 30th, 2012 11:40 pm

    This will be the proper weblog for hopes to determine about this topic.
    You have been aware of so much it can be just about arduous
    to argue along with you not that I really would wantHaHa.

    You definitely put a brand new spin on the topic thats been discussed for some time.
    First-rate stuff, just good!

  33. on August 5th, 2012 4:17 pm

    Appreciate it for this post, I am a big fan of this internet site want to proceed

  34. on August 13th, 2012 1:58 pm

    Thanks a ton for the time to have decided to
    put these things together on this website. Janet
    and I greatly treasured your suggestions through your blog on certain things.
    I understand you to have a number of demands on program and so that the
    fact that an individual like you took just because
    much time such as you did to help viewers for example us via this blog
    is even extremely loved.

  35. how to lose weight fast on August 13th, 2012 4:56 pm

    oh i just hate that the fat pads that i got, my fat pad is just genetics so i cant do anything about it

  36. cell phone lookup on August 20th, 2012 3:01 am

    Awesome! I thank you your contribution to this matter. It has been
    insightful. my blog maple syrup

  37. reverse phone lookup cell on August 24th, 2012 2:16 am

    Blaine is not the best magician but i can say
    that he has great showmanship and i like his

  38. cell phone lookup on August 24th, 2012 3:30 am

    clay garden pots have been great then again when you want a less expensive alternative, you can always use
    those plastic garden pots