What is the actual purpose of std::type_info::name()?

后端 未结 2 1573
梦谈多话
梦谈多话 2020-12-05 05:05

Today a colleague of mine came and asked me the question as mentioned in the title.
He\'s currently trying to reduce the binaries footprint of a codebase, that is also u

相关标签:
2条回答
  • 2020-12-05 05:21

    Are there real life, production code level use cases for std::type_info::name() other than logging?

    The Itanium ABI describes how operator== for std::type_info objects can be easily implemented in terms of testing strings returned from std::type_info::name() for pointer equality.

    In a non-flat address space, where it might be possible to have multiple type_info objects for the same type (e.g. because a dynamic library has been loaded with RTLD_LOCAL) the implementation of operator== might need to use strcmp to determine if two types are the same.

    So the name() function is used to determine if two type_info objects refer to the same type. For examples of real use cases, that's typically used in at least two places in the standard library, in std::function<F>::target<T>() and std::get_deleter<D>(const std::shared_ptr<T>&).

    If you're not using RTTI then all that's irrelevant, as you won't have any type_info objects anyway (and consequently in libstdc++ the function::target and get_deleter functions can't be used).

    I think GCC's exception-handling code uses the addresses of type_info objects themselves, not the addresses of the strings returned by name(), so if you use exceptions but no RTTI the name() strings aren't needed.

    0 讨论(0)
  • 2020-12-05 05:27

    Isolating this bit:

    • The point is, if they switch off RTTI, will exception handling still work properly in GCC? — πάντα ῥεῖ 1 hour ago

    The answer is yes:

    -fno-rtti

    Disable generation of information about every class with virtual functions for use by the C++ runtime type identification features (dynamic_cast and typeid). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but it will generate it as needed. The dynamic_cast operator can still be used for casts that do not require runtime type information, i.e. casts to void * or to unambiguous base classes.

    0 讨论(0)
提交回复
热议问题