Class factories and shared_ptr<T>
One way to control object memory and initialization is to wrap object creation in a class factory. This is the point of the proposed make_shared<T>(..) and allocate_shared<T>(..) standard library functions.
But it is easy to roll your own simple factory function:
# include <boost/shared_ptr.hpp>
using boost::shared_ptr;
class
factory_type
{
/* this_type type alias */
private:
typedef
factory_type
this_type;
// ======== Disable Copy ============
/* disabled copy ctor */
private:
factory_type( this_type const &)
; /* no implementation */
/* disabled copy assignment */
private:
void
operator =( this_type const &)
; /* no implementation */
// ======== Factory =================
/* private default ctor */
private:
factory_type( )
{ }
/* public (unfortunately) dtor */
public:
~factory_type( )
{ }
/* factory, only way to make these objects */
public:
static
shared_ptr< this_type >
make_new( )
{ return
shared_ptr< this_type >(
new this_type);
}
};
shared_ptr< factory_type >
factory_inst(
factory_type::make_new( ));
And there you have factor_type, a tightly controlled class where all insts are created in the factory (factory_type::make_new( )) and all deletes are through shared_ptr<T>s. The private constructors means not only can we not “new” the class ourselves, we also cannot use it as a supertype. Nor can we declare a factory_type class member or stack variable.
factor_type would be improved, however, if we could ensure that only shared_ptr<T>s could access the destructor. It doesn’t work to declare the destructor private and friend class shared_ptr< this_type > because the destructor is actually called from a deleter function. However we can friend the deleter function:
class
factory_type
{
... as above ...
/* private dtor */
private:
~factory_type( )
{ }
/* the only function that calls the dtor */
friend void boost::checked_delete( this_type *);
/* factory, only way to make these objects */
public:
static
shared_ptr< this_type >
make_new( )
{ return
shared_ptr< this_type >(
new this_type);
}
};
This works fine, but you get the following warning from msvc++9.0: the inline specifier cannot be used when a friend declaration refers to a specialization of a function template. Of course you can disable this warning. It’s not very important and likely to go away in a future version of msvc++ anyway, and it may even be corrected by an optimized non-debug compile.
The nicest solution, however, is to provide a private non-templated deleter. It doesn’t issue the above warning and it feels more portable. It’s only drawback is that it slightly increases the size of the intermediate ref-count object.
class
factory_type
{
... as above ...
/* private dtor */
private:
~factory_type( )
{ }
/* the only place where the dtor is used */
private:
struct
private_deleter
{ void
operator ()( this_type * p)
{ delete p; }
};
/* factory, only way to make these objects */
public:
static
shared_ptr< this_type >
make_new( )
{ return
shared_ptr< this_type >(
new this_type,
private_deleter( ));
}
};
Comments
40 Responses to “Class factories and shared_ptr<T>”
Thanks– this came in very handy!
Great article, thanks. I signed up to your blog rss feed.
ther are plenty of outdoor decors out there on the local hardware then again we always use outdoor decors coming from recyclable materials
senior living can be costly when you have not found a very first-rate business or that offers a great deal,
Pretty nice post, thanks for that the awesome article.
Im having troubles subscribing to your internet
sites feed. Thought Id let you recognize
i am a fan of most us tv shows something like Oprah and Ellen, i really enjoy watching tv
shows,.
home repair can be challenging specially if you do not have any idea at all about what
you have been doing,,
Determine upset! Only letting the quota happen isnt acceptable.
This will help you stay above that the curve.
It’s astounding, seeking within the time and work you place into your weblog and detailed specifics you furnish. Ill bookmark your web site and pay a visit to it weekly for the new posts.
leather jackets can actually make you look excellent, that they also make you feel warm and
comfortable,,
Wonderful blog! I found it while searching on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there! Appreciate it
Its laborious to find educated individuals on this subject, then again you sound
for example you know what youre talking about! Thanks
my father started a calorie restriction diet and all i can say is that it
helped him to reduce body fats
I gotta bookmark this web site it seems very useful very beneficial
I conceive this site has very fantastic pent subject material blog posts.
Im not in a position to view this website correctly
on saffari I think theres a drawback
If you would like to increase your knowledge simply keep visiting this site and be updated with the latest news posted here.
Hello! I simply would would along the lines of to supply
a large thumbs up with the excellent info youve here on this post.
We are coming back to your blog site for much more soon.
When I originally commented I clicked the Notify me when new comments
are added checkbox and already if a comment is added I determine four emails with
that the exact same comment. Possibly there is by any means you have
been able to remove me from that service Thanks!
Very descriptive article, I liked that a lot. Will there be a part
2?
I blog often and I truly appreciate your content. Your article has truly peaked my
interest. I’m going to book mark your website and keep checking for new details about once a week. I opted in for your RSS feed too.
Some actually interesting details you have written. Aided me a large amount,
just what I was hunting for .
I am curious to obtain out what blog technique youre
by employing Im experiencing some tiny security problems with my latest blog and I would for instance to search for something more riskfree.
Do you have any other recommendations
This is actually smart blog. I imply it. You have so much knowledge about this issue, and so first-rate deal passion.
You also recognize ideal make ladies rally behind it, obviously out of that the responses.
Youve obtained a style here thats not too flashy, in spite of this
makes a statement because big as what youre saying.
Excellent work, indeed.
I Just stopped by to say your article is great. That the
clarity in your post is only spectacular and i can assume youre an
expert on this subject. First-rate with your permission let me to grab your RSS feed to keep existing with forthcoming post.
Thanks a million and please continue that the enjoyable
work.
dependant upon fossil fuel is always a bad idea, we should always concentrate on
renewable energy.
I discovered your blog website on google and examine a quantity of of your early posts.
Proceed to maintain up that the very first-rate operate.
I simply further up your RSS feed to my MSN Info Reader.
Looking for forward to studying extra from you in a while!
Im normally to running a blog and i really respect your content.
The article has really peaks my interest. I am going to bookmark your site
and hold checking for brand new information.
Spot on with this writeup, I genuinely feel this website wants far more consideration.
Ill possibly be once more to read much more, thanks for the information.
Respect to article author , some wonderful information .
I truly appreciate this post. I have been looking
everywhere for this! Thank God I found it on Bing. You have made
my day! Thanks again.
Comfortabl y, the post is actually the freshest on that deserving topic.
I harmonise with your conclusions and also will thirstily look
forward to your next updates. Just saying thanks will certainly not only
be acceptable, for that the extraordinary clarity in your writing.
I will directly grab your rss feed to stay informed of any other
updates. Gratifying work and far success in your business dealings!
Do you write more It only required a couple of moments
to see your entry and so have an awareness that I be acquainted with most people miss out on.
Getting more people to join that the discussion is normally a great thing.
i hate artifical stuffs so i always do organic gardening at home to look for some natural foods“
There have been a couple of interesting points on time in this posting conversely I do not know if these center to
heart. Theres some validity in spite of this I will take hold opinion until I
explore it further. Great article , thanks and now we want
more! Combined with FeedBurner also
get a hold of dining might be expensive on the other hand that
the menu and service is always the best.
heya. I notice that youre most likely interested in building
backlinks and stuff. Im promoting scrapebox auto
approve link lists. If youd such as to trade
Magnificent goods out of you, man. I have understand your stuff prior to
and youre just too wonderful. I actually like what you have acquired here, really something like what youre saying and that
the system in which you say it. You make it entertaining and you still take care of to keep it wise.
I cant wait to read much more out of you. This is really a terrific site.
Bonsoir à vous Vous ne croyez pas que les
arguments de votre post ont besoin de nouvelles valeurs Votre démarche semble bonne quoique je ne comprends pas les différents avis ci dessus.
Pensez a rajouter dautres affirmations pour plus de professionalisme!
Au plaisir de vous relire
There have been a handful of interesting points with time in this article then again I
do not determine if I see every one of them center to heart.
Theres some validity but I am going to take hold opinion until I investigate it
further. Fine article , thanks so we want a lot more! Added to FeedBurner likewise
This design is incredible! You obviously know how to keep
a reader amused. Between your wit and your videos,
I was just about moved to start my own blog well, almostHaHa!
Good job. I actually enjoyed what you had to say, and more than that,
how you presented it. Too cool!