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>”

  1. Anu Pakanati on July 17th, 2011 1:33 pm

    Thanks– this came in very handy!

  2. http://criminalbackgroundchecked.com/ on July 4th, 2012 12:08 pm

    Great article, thanks. I signed up to your blog rss feed.

  3. 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 sm on July 8th, 2012 2:05 pm

    ther are plenty of outdoor decors out there on the local hardware then again we always use outdoor decors coming from recyclable materials

  4. grants for single mothers on July 8th, 2012 3:26 pm

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

  5. free money for single mothers on July 8th, 2012 4:07 pm

    Pretty nice post, thanks for that the awesome article.
    Im having troubles subscribing to your internet
    sites feed. Thought Id let you recognize

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

    i am a fan of most us tv shows something like Oprah and Ellen, i really enjoy watching tv
    shows,.

  7. scholarships for single teenage mothers on July 8th, 2012 4:54 pm

    home repair can be challenging specially if you do not have any idea at all about what
    you have been doing,,

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

    Determine upset! Only letting the quota happen isnt acceptable.
    This will help you stay above that the curve.

  9. free reverse cell phone lookup google on July 10th, 2012 4:22 am

    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.

  10. http://officialreversephonelookup.com/ on July 16th, 2012 12:40 pm

    leather jackets can actually make you look excellent, that they also make you feel warm and
    comfortable,,

  11. http://www.prlog.org/11734629-phone-number-search-reverse-number-lookup.html on July 16th, 2012 12:56 pm

    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

  12. http://www.prlog.org/11161236-cell-phone-number-lookup-free-can-you-really-get-one-for-free.html on July 16th, 2012 1:59 pm

    Its laborious to find educated individuals on this subject, then again you sound
    for example you know what youre talking about! Thanks

  13. http://ezinearticles.com/?Free-Reverse-Phone-Lookup---Answer-To-The-Myth-About-Free-Cell-Phone-Number-Lookups&id=5986059 on July 16th, 2012 2:21 pm

    my father started a calorie restriction diet and all i can say is that it
    helped him to reduce body fats

  14. http://www.prlog.org/11734648-criminal-background-check-public-records.html on July 16th, 2012 3:08 pm

    I gotta bookmark this web site it seems very useful very beneficial

  15. http://www.youtube.com/watch?v=c3-A_ZxBlSQ on July 16th, 2012 4:46 pm

    I conceive this site has very fantastic pent subject material blog posts.

  16. http://www.prlog.org/11306749-phone-number-lookup-got-cheating-wife-on-your-hands.html on July 16th, 2012 5:51 pm

    Im not in a position to view this website correctly
    on saffari I think theres a drawback

  17. cell phone directory on July 16th, 2012 8:14 pm

    If you would like to increase your knowledge simply keep visiting this site and be updated with the latest news posted here.

  18. phone number on July 16th, 2012 8:16 pm

    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.

  19. reverse address lookup on July 16th, 2012 8:47 pm

    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!

  20. reverse phone lookup on July 16th, 2012 9:02 pm

    Very descriptive article, I liked that a lot. Will there be a part
    2?

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

    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.

  22. http://ezinearticles.com/?Reverse-Phone-Lookup---Easy-Way-to-Know-the-Truth&id=5909597 on July 17th, 2012 2:01 am

    Some actually interesting details you have written. Aided me a large amount,
    just what I was hunting for .

  23. people finder on July 17th, 2012 2:27 am

    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

  24. http://ezinearticles.com/?Phone-Number-Search---Stopping-a-Cheater-the-Easy-Way&id=5909547 on July 17th, 2012 2:33 am

    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.

  25. reverse phone lookup on July 18th, 2012 1:37 am

    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.

  26. http://www.prlog.org/11261550-phone-number-lookup-catch-cheater-quickly.html on July 25th, 2012 1:55 am

    dependant upon fossil fuel is always a bad idea, we should always concentrate on
    renewable energy.

  27. ways to make money on July 27th, 2012 6:29 am

    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.

  28. http://www.reversephonelookuped.com/ on August 5th, 2012 9:17 pm

    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.

  29. reverse phone lookup on August 10th, 2012 9:18 pm

    Respect to article author , some wonderful information .

  30. reverse phone lookup on August 10th, 2012 9:41 pm

    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.

  31. reverse phone lookup on August 10th, 2012 9:51 pm

    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!

  32. phone number lookup on August 10th, 2012 10:09 pm

    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.

  33. phone number lookup on August 10th, 2012 10:23 pm

    i hate artifical stuffs so i always do organic gardening at home to look for some natural foods“

  34. reverse phone on August 10th, 2012 10:27 pm

    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

  35. reverse phone lookup on August 10th, 2012 10:32 pm

    get a hold of dining might be expensive on the other hand that
    the menu and service is always the best.

  36. cell phone lookup on August 13th, 2012 11:20 am

    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

  37. http://411howtoloseweightfast.com/ on August 13th, 2012 12:37 pm

    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.

  38. cell phone lookup on August 16th, 2012 3:47 pm

    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

  39. cell phone lookup on August 19th, 2012 10:21 pm

    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

  40. reverse phone lookup on August 23rd, 2012 7:26 pm

    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!