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.
struct
some_type
{ };
// Deleter that works when you create
// some_type with operator new.
struct
some_type_deleter
{ 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 >
sp_1(
new some_type);
// Boost provides a standard deleter struct
// that calls boost::checked_delete<T>(..).
shared_ptr< some_type >
sp_2(
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 >
sp_3(
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 >
struct
array_deleter
{
void
operator ()( T const * p)
{ delete[] p; }
};
// Example target object
struct
my_type
{ my_type( ) { balance += 1; }
~my_type( ) { balance -= 1; }
static int balance;
};
int my_type::balance = 0;
int
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 >
sp_array(
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 > sp_array_inst( 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 > > sp_array2( 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.
Comments
38 Responses to “Arrays, shared_ptr< T >s, and deleters”
[...] 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 [...]
senior living can be costly if you have not found a very first-class business or that
offers a great deal,
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.
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.
The script, cowritten by McKay & Chris Henchy, sends
up buddy cop movies with more verve than most films of this type.
i am seeking for gadget reviews this december coz i wanna buy
some of the latest gadgets for my girlfriend
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.
A lot of thanks for this kind of facts I had been hunting all Lookup engines to discover it!
soem internet sites that provide download games have viruses and spywares on it.
so make sure to have some antivirus on your PC,,
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.
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.
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
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
read?
When visiting internet sites, i always look for a very
nice content for example yours ,
very fine post, i definitely adore this amazing site, persist
with it
i would always be a fan of Nip/Tuck, i was saddened about that the
episode when one of the doctors got breast cancer
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.
When visiting web pages, i always look for a very
nice content like yours ,
Thank you, Ive recently been searching for info about this subject for ages and yours is that the best I have located so far.
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!
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!
Thank you for this specific facts I was basically looking
all Bing to uncover it!
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.
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.
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.
Universial Studios offers one of the best studio in Hollywood,
they also make great films
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.
By how you compose, an person appear to be an expert author.
dress shops that present discounts are very wide-ranging in our
place and i always shop at them
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
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.
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!
Appreciate it for this post, I am a big fan of this internet site want to proceed
updated.
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.
oh i just hate that the fat pads that i got, my fat pad is just genetics so i cant do anything about it
Awesome! I thank you your contribution to this matter. It has been
insightful. my blog maple syrup
Blaine is not the best magician but i can say
that he has great showmanship and i like his
show
clay garden pots have been great then again when you want a less expensive alternative, you can always use
those plastic garden pots