Using static_pointer_cast<T>(..) and dynamic_pointer_cast<T>(..)

This demonstrates how to use static_pointer_cast<T>(..) and dynamic_pointer_cast<T>(..). It is like the previous post which shows how to use const_pointer_cast<T>(..).

First the headers and some class declarations:

# include <boost/assert.hpp>
# include <boost/pointer_cast.hpp>
# include <boost/shared_ptr.hpp>
using boost::shared_ptr;
using boost::static_pointer_cast;
using boost::dynamic_pointer_cast;

  class
base_type
  { public: virtual ~base_type( ) { } };

  class
derived_type
  : public base_type
  { };

  class
derived_type_other
  : public base_type
  { };

Notice base_type has a virtual destructor, which makes it a polymorphic class. A class has to have at least one virtual method if you want to use it with dynamic_pointer_cast<T>(..). Otherwise the compiler complains loudly.

Remember that, in general, declaring the destructors virtual is often not necessary if a class is being managed by shared_ptr<T>. If you always immediately attach a new target object to a shared_ptr< MOST_DERIVED_CLASS > after creation, then you don’t have to worry if shared_ptr< BASE_CLASS > later deletes that target object. The most-derived destructor is bound to the shared_ptr<T> during first attach and is passed along to subsequent shared and weak pointers.

Finally, here is the code showing static_pointer_cast<T>(..) and dynamic_pointer_cast<T>(..).

  // Make a shared_ptr to a new object.
  shared_ptr< derived_type >
sp_derived(
  new derived_type);

  // The shared_ptr knows how to upcast its
  // inner pointer.
  shared_ptr< base_type >
sp_base(
  sp_derived);

  // You can static-downcast the inner pointer.
  shared_ptr< derived_type >
sp_derived2(
  static_pointer_cast< derived_type >( sp_base));

  // You can dynamic-downcast the inner pointer
  // as long as the inner type is polymorphic.
  shared_ptr< derived_type >
sp_derived3(
  dynamic_pointer_cast< derived_type >( sp_base));
  BOOST_ASSERT( sp_derived3);

  // You can try to dynamic-downcast to the wrong type.
  // You will end up with a null shared_ptr because
  // the inner dynamic-downcast returns a zero pointer.
  // This does not throw std::bad_cast because it casts
  // pointers and not refs.
  shared_ptr< derived_type_other >
sp_derived_other(
  dynamic_pointer_cast< derived_type_other >( sp_base));
  BOOST_ASSERT( ! sp_derived_other);

Like const_pointer_cast<T>(..), static_pointer_cast<T>(..) and dynamic_pointer_cast<T>(..) also work with intrusive_ptr<T>s and raw pointers. But they don’t work with weak_ptr<T>, at least not in Boost 1_37_0 (I suspect it’s an oversight). They also do not work with shared_array<T>, which makes sense since array “pointers” should always be to the most-derived type, and of course they don’t work with the single-ownership smart pointers that don’t support normal copy semantics.

There is also a reinterpret_pointer_cast<T>(..) function, but it only works with raw pointers. Reinterpret cast is usually only used at a very low abstraction level, while smart pointers are highly abstracted. If you think you need a reinterpret cast with a smart pointer you are probably doing something wrong.

Comments

28 Responses to “Using static_pointer_cast<T>(..) and dynamic_pointer_cast<T>(..)”

  1. http://criminalbackgroundchecked.com/ on July 4th, 2012 12:07 pm

    I are 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 info 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.

  2. ourmidland view website on July 7th, 2012 8:51 am

    It is perfect time to make some plans for that the future and
    its time to be happy. Ive read this post and if
    I could I desire to suggest you few interesting things or tips.

    Maybe you could write next articles referring to this article.
    I would something like to read more things about it!

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

    Thankyou for helping out, wonderful info .

  4. 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 ss on July 8th, 2012 2:04 pm

    I really along the lines of your wordpress design, wherever do you download
    it from

  5. free grants for single mothers on July 8th, 2012 3:24 pm

    This web page wont render properly on my blackberry you might want to utilize and repair that

  6. free assistance for single mothers on July 8th, 2012 4:06 pm

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

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

    I come up reference an olive offshoot in solitary around, and
    that the freedom fighters gun in that the other. Do not detonate that
    the olive limb become lower out of my hand.

  8. college scholarships and grants for single mothers on July 8th, 2012 4:53 pm

    REMEMBERthis is the man who removed that the American flag from his airplane during the
    campaign nd replaced it with a Pepsitype flag of his own.

    That was the first warning to us.

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

    foot massage have been very relaxing, i love to have a foot massage after a
    demanding days work

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

    very nice publish, i definitely love this website, carry on it

  11. http://officialreversephonelookup.com/ on July 16th, 2012 12:39 pm

    We stumbled over here by an additional page and thought I might check things out.

    I for instance what I see so now im following you.
    Look forward to searching for about your web page for a second time.

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

    Hello to all, the contents present at this web site are actually remarkable for
    people experience, well, keep up the nice work fellows.

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

    power tools can really save you out of a lot of headache,
    specially when the job is very hard,

  14. criminal background check on July 16th, 2012 2:58 pm

    There a few interesting points in time in this article on the other hand I do not find
    out if I see these people center to heart.

    There exists some validity however I will
    take hold opinion until I consider it further. Great article ,
    thanks and that we want far more! Added onto FeedBurner too

  15. http://www.prlog.org/11674605-reverse-phone-lookup-finders.html on July 16th, 2012 3:18 pm

    Today, I went to the beach with my children. I
    found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

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

    Employee relations should be given more importance in
    an office environment as well as on any other company establishment.

  17. phone number lookup on July 16th, 2012 5:23 pm

    Im not positive that the place you are getting your info, conversely great topic.
    I must spend a while looking up much more or
    figuring out more. Thank you for magnificent info I was in lookup of this information for my mission.

  18. reverse phone directory on July 16th, 2012 8:13 pm

    whoah this blog is wonderful i like reading your posts.
    Stay up the great work! You already know, many persons
    are looking around for this information, you can aid them greatly.

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

    designer shoes have been of course very expensive then again
    i like their style,

  20. http://ezinearticles.com/?Reverse-Address-Lookup---Get-the-Information-You-Need-the-Easy-Way&id=5909554 on July 16th, 2012 8:46 pm

    I discovered your site site on bing and check a few your early
    posts. Always maintain that the great operate.
    I just extra increase RSS feed to my MSN News Reader. Searching for forward to reading much more on your part
    down that the road!

  21. reverse phone lookup on July 16th, 2012 9:00 pm

    WOW just what I was searching for. Came here by searching for reverse phone lookup

  22. reverse phone on July 17th, 2012 2:00 am

    Id must seek answers from you here. Which just
    isn’t something Which i do! I love reading an article which will make people feel. Also, thank you for allowing me to comment!

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

    Can I say what a relief to discover somebody who actually knows what theyre talking about via the internet.
    You really know how to bring a problem to light and work out it essential.
    Workout . must check out this and understand why side out of that the
    story. I cant think youre no more general since you also undoubtedly possess the gift.

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

    I precisely wanted to appreciate you all over again.
    Im not certain the things that I wouldve followed without those information shared by you on that theme.

    It had been an absolute frightful crisis in my circumstances,
    then again discovering an alternative skilled approach
    you managed that forced me to cry with joy. I am just thankful for this support and then believe you know what an
    amazing job you are always doing training a lot of others all through your
    site. I know someone to havent got to identify any of us.

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

    the Gilmore Girls are really gorgeous, and that is the main reason
    why i watch that tv show.

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

    It’s demanding to obtain knowledgeable individuals within this topic, on the other hand you be understood because guess what happens youre discussing! Thanks

  27. http://www.prlog.org/11936100-reverse-phone-lookup-to-trace-any-number.html on July 29th, 2012 12:12 pm

    Wonderful site. I hope you write more informative articles, because i will check back often
    to read your posts.

  28. cell phone lookup on August 20th, 2012 8:34 am

    The that the next occasion Someone said a blog, I hope whos doesnt disappoint
    me up to this one. Figure out real, I know it was my substitute
    for read, in spite of this I actually thought youd have some thing intriguing to convey.

    All I hear is really a handful of whining about something that you could fix in the
    event you werent too busy seeking for attention.