c – 什么时候canid可以为同一类型返回不同的type_info实例?

Andrei Alexandrescu写于Modern C++ Design

The objects returned by typeid have
static storage, so you don’t have to
worry about lifetime issues.

安德烈继续说:

The standard does not guarantee that
each invocation of, say, typeid(int)
returns a reference to the same
type_info object.

即使标准不能保证这一点,如何在常见的编译器中实现,例如GCC和Visual Studio?

假设typeid没有泄漏(并且每次调用都返回一个新实例),每个应用程序,每个转换单元,每个dll / so或者完全不同的东西,它是一个“表”吗?

是否有& typeid(T)!=& typeid(T)?

我主要对Windows的编译器感兴趣,但是对于Linux和其他平台的任何信息也很感激.

解决方法:

Are there times when &typeid(T) != &typeid(T)?

I’m mainly interested in compilers for Windows, but any information for Linux and other platforms is also appreciated.

是.在windows下DLL不能有未解析的符号,因此.如果你有:

foo.h中

struct foo { virtual ~foo() {} };

dll.cpp

#include "foo.h"
...
foo f;
cout << &typeid(&f) << endl

main.cpp中

#include "foo.h"
...
foo f;
cout << &typeid(&f) << endl

会给你不同的指针.因为在加载dll之前,应该存在typeid(foo)
在dll和主要exe中

更重要的是,在Linux下,如果主可执行文件未使用-rdynamic(或–export-dynamic)编译,那么typeid将被解析为可执行文件中的不同符号
在共享对象中(通常不会在ELF平台下发生),因为在链接可执行文件时进行了一些优化 – 删除了不必要的符号.

上一篇:c – RTTI与例外之间是否存在关联?


下一篇:RTTI