什么时候可以返回不同的type_info实例为同一类型? [英] When can typeid return different type_info instances for same type?

查看:148
本文介绍了什么时候可以返回不同的type_info实例为同一类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Andrei Alexandrescu 现代C ++设计


typeid 返回的对象有
静态存储,因此您不必担心
担心生命周期


Andrei继续:


该标准不保证
每次调用,例如 typeid(int)
返回一个引用
type_info object。


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



假设 typeid 调用),每个应用程序,每个转换单元,每dll / so,或完全不同的一个表?



有时候& typeid(T)!=& typeid(T)



我主要感兴趣的是Windows编译器,

解决方案


有时候& typeid T]!=& typeid(T)?



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

是的。在Windows下,DLL不能有未解析的符号,因此。如果您有:



foo.h

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

dll.cpp

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

main.cpp

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

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



更多的是,在Linux下,如果主可执行文件没有编译-rdynamic(或--export-dynamic)然后typeid将被解析为不同的符号在可执行文件和
在共享对象(通常不会发生在ELF平台下),因为一些优化完成时链接可执行文件 - 删除不必要的符号。


Andrei Alexandrescu writes in Modern C++ Design:

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

Andrei continues:

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

Even though the standard does not guarantee this, how is this implemented in common compilers, such as GCC and Visual Studio?

Assuming typeid does not leak (and return a new instance every call), is it one "table" per application, per translation unit, per dll/so, or something completely different?

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.

解决方案

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.

Yes. Under windows DLL can't have unresolved symbols, thus. If you have:

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

Would give you different pointers. Because before dll was loaded typeid(foo) should exist in both dll and primary exe

More then that, under Linux, if main executable was not compiled with -rdynamic (or --export-dynamic) then typeid would be resolved to different symbols in executable and in shared object (which usually does not happen under ELF platforms) because of some optimizations done when linking executable -- removal of unnecessary symbols.

这篇关于什么时候可以返回不同的type_info实例为同一类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆