Why is RTTI necessary?

后端 未结 2 1490
一生所求
一生所求 2021-01-07 06:34

Why is RTTI (Runtime Type Information) necessary?

2条回答
  •  余生分开走
    2021-01-07 06:58

    I can think of exactly one case when it would be appropriate to use RTTI, and it doesn't even work.

    It is fairly common for C-compatible APIs which perform callbacks to provide a user-defined void* to communicate a state structure back to the caller. When calling such an API from C++, it is quite common to pass the this pointer through said void* argument. From the callback, one might want to invoke virtual functions on the passed pointer.

    In some cases when the callback parameters are insecure (such as LPARAM of a Windows message), it is obviously desirable to validate the pointer before using it for a virtual call, by checking the hidden vfptr. dynamic_cast is the natural way to do this, but results in undefined behavior exactly when the object is invalid (IIRC, it is undefined behavior if the pointer is to anything except an object with a virtual table). So RTTI is utterly useless for preventing a shatter attack in this way.

    Feel free to present any other valid use cases for RTTI, cause I'm totally unconvinced.

    EDIT: boost::any got mentioned. As far as boost::any is concerned, you can disable RTTI and use the following typeid implementation:

    typedef const void* typeinfo_nonrtti;
    template  typeinfo_nonrtti typeid_nonrtti();
    template  class typeinfo_nonrtti_helper
    {
      friend typeinfo_nonrtti typeid_nonrtti();
      static char unique;
    };
    template  char typeinfo_nonrtti_helper::unique;
    
    template 
    typeinfo_nonrtti typeid_nonrtti() { return &typeinfo_nonrtti_helper::unique; }
    

提交回复
热议问题