Why is 'pure polymorphism' preferable over using RTTI?

前端 未结 7 692
清歌不尽
清歌不尽 2020-12-04 08:59

Almost every C++ resource I\'ve seen that discusses this kind of thing tells me that I should prefer polymorphic approaches to using RTTI (run-time type identification). In

7条回答
  •  -上瘾入骨i
    2020-12-04 09:32

    Of course there is a scenario where polymorphism can't help: names. typeid lets you access the name of the type, although the way this name is encoded is implementation-defined. But usually this is not a problem since you can compare two typeid-s:

    if ( typeid(5) == "int" )
        // may be false
    
    if ( typeid(5) == typeid(int) )
       // always true
    

    The same holds for hashes.

    [...] RTTI is "considered harmful"

    harmful is definitely overstating: RTTI has some drawbacks, but it does have advantages too.

    You don't truly have to use RTTI. RTTI is a tool to solve OOP problems: should you use another paradigm, these would likely disappear. C doesn't have RTTI, but still works. C++ instead fully supports OOP and gives you multiple tools to overcome some issue that may require runtime information: one of them is indeed RTTI, which though comes with a price. If you can't afford it, thing you'd better state only after a secure performance analysis, there is still the old-school void*: it's free. Costless. But you get no type safety. So it's all about trades.


    • Some compilers don't use / RTTI is not always enabled
      I really don't buy this argument. It's like saying I shouldn't use C++14 features, because there are compilers out there that don't support it. And yet, no one would discourage me from using C++14 features.

    If you write (possibly strictly) conforming C++ code, you can expect the same behavior regardless of the implementation. Standard-compliant implementations shall support standard C++ features.

    But do consider that in some environments C++ defines («freestanding» ones), RTTI need not be provided and neither do exceptions, virtual and so on. RTTI needs an underlying layer to work correctly that deals with low-level details such as the ABI and the actual type information.


    I agree with Yakk regarding RTTI in this case. Yes, it could be used; but is it logically correct? The fact that the language allows you to bypass this check does not mean it should be done.

提交回复
热议问题