c++ - std::type_info::name() 的实际目的是什么?

标签 c++ c++11 gcc

今天有个同事来问我标题中提到的问题。
他目前正在尝试减少代码库的二进制占用空间,该代码库也用于小型目标(如 Cortex M3 等)。显然他们已经决定在打开 RTTI 的情况下进行编译(实际上是 GCC),以支持正确的异常处理。

嗯,他的主要提示是为什么 std::type_info::name() 实际上完全需要支持 RTTI,并问我是否知道一种方法来抑制生成支持这一点所需的字符串文字,或者至少缩短它们。

std::type_info::name

const char* name() const; Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

A ,- 但是编译器特定的-,例如的实现dynamic_cast<>运算符(operator)不会使用此信息,而是使用类似于哈希标签的东西来确定类型(类似于 catch() 具有异常处理的 block )。
我认为后者在当前的标准定义中明确表达了

  1. std::type_info::hash_code
  2. std::type_index

我不得不同意,我也没有真正看到使用 std::type_info::name() 的意义。 ,而不是用于调试(记录)目的。我不是 100% 确定在当前版本的 GCC(我认为他们使用的是 4.9.1)的情况下,仅在没有 RTTI 的情况下异常处理也能正常工作,所以我犹豫是否建议直接关闭 RTTI。
dynamic_casts<> 也是这种情况。在他们的代码库中使用,但对于这些,我只是建议不要使用它,支持 static_cast (它们实际上没有插件之类的东西,或者除了断言之外不需要运行时类型检测)。


问题:

  • 是否有 std::type_info::name() 的实际生产代码级用例?除了日志记录?

子问题(更具体):

  • 有没有人知道如何克服(解决)这些无用字符串文字的生成(假设它们永远不会被使用)?

  • 真的(仍然)需要 RTTI 来支持 GCC 的异常处理吗?
    (这部分现在由 @Sehe's answer 很好地解决了,我已经接受了。对于代码中使用的任何异常,剩余生成的 std::type_info 实例仍然存在另一个子问题。我们很确定,这些文字永远不会在任何地方使用)


相关位: Strip unused runtime functions which bloat executable (GCC)

最佳答案

隔离这个位:

answer是的:

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

关于c++ - std::type_info::name() 的实际目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28861760/

相关文章:

c++ - G++ 忽略 _Pragma 诊断被忽略

c++ - 在线程之间 move vector

编译器在打印变量地址时发出警告

c++ - 错误 : strstream. h:没有那个文件或目录

c++ - 在 Qt 中将文件保存到网络

c++ - 查找未排序数组的主导模式

c++ - 在编译时生成唯一编号

c++ - 如何在 std::bind 中指示给定签名的重载函数?

c++ - 如何在我的 Ubuntu 11.04 (Natty Narwhal) 上安装 g++/gcc 4.6?

c++ - 发送文件时套接字写入失败