The practical use of dynamic_cast in reusable or generic code

Discussion in 'C++' started by Axter, May 9, 2005.

  1. Axter

    Axter Guest

    I'm wondering about the practical use of dynamic_cast in reusable or
    generic code.
    I'm currently working on a smart pointer that can be used on vector
    and other STL containers.
    See following link:
    http://code.axter.com/arr_ptr.h

    In above code, there's a function called clone_func_ptr_interface
    within the func_ptr_holder class.
    In this function, I need to cast from a base pointer to a derived
    pointer.
    I originally used dynamic_cast, but then I realized it would force
    anyone using the code to enable RTTI.

    I was also worried that using dynamic_cast would make my code less
    efficient.

    Considering that most projects don't have RTTI enabled, and that
    dynamic_cast could result in less efficient code, how practical is it
    to use dynamic_cast in reusable or generic code?
    Should it be avoided in this type of code, or should it be used
    regardless of how less reusable it makes the code?
     
    Axter, May 9, 2005
    #1
    1. Advertisements

  2. If it isn't enabled, virtual functions won't work and you no longer have
    standard C++. If that's the case you are by definition off-topic here
    :-(
    Did you measure it?
    dynamic_cast is provided because it does something none of the other
    casts can do. If you need that functionality, never mind "practical",
    it's *necessary*. If that's the case, any workaround is likely to be
    even less efficient.
    Is it *needed*?
     
    Richard Herring, May 12, 2005
    #2
    1. Advertisements

  3. Axter

    Axter Guest

    You don't need to have RTTI enable to have virtual functions working.
    The virtual functions work without RTTI enabled.
    The point is, that the code can work without dynamic_cast, but
    dynamic_cast could add extra runtime type safety.

    So what I'm weighing is the difference between adding extra runtime
    type safety and loosing efficiency as well as loosing reuse.
     
    Axter, May 13, 2005
    #3
  4. Then you must mean something different from me by "RTTI". It doesn't
    matter, anyway. I'll rephrase the above.

    If dynamic_cast isn't enabled, you no longer have standard C++. If
    that's the case you are by definition off-topic here.
    Then _weigh_ it. So far you're just _talking_ about it. Have you
    actually measured the efficiency loss?
    Standard C++ provides dynamic_cast, so that's not a genuine issue.
     
    Richard Herring, May 13, 2005
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.