Can type_info pointers be used to distingush types in C++?

好久不见. 提交于 2020-01-15 23:13:24

问题


I have a set of polymorphic C++ classes and they are all instantiated by the same module (Windows DLL). Now having two pointers to such classes and having called typeid:

SomeCommonBase* first = ...; //valid pointer
SomeCommonBase* second = ...; //valid pointer
const type_info& firstInfo = typeid( first );
const type_info& secondInfo = typeid( second );

can I compare retrieved type_info addresses

if( &firstInfo == &secondInfo ) {
   //objects are of the same class
} else {
   //objects are of different classes
}

or use ==

if( firstInfo == secondInfo ) {
   //objects are of the same class
} else {
   //objects are of different classes
}

to detect whether objects are of (exactly) the same class or of different classes? Is it guaranteed to work when objects are instantiated from within the same module?


回答1:


As I'm writing this, your code is

SomeCommonBase* first = ...; //valid pointer
SomeCommonBase* second = ...; //valid pointer
type_info& firstInfo = typeid( first );
type_info& secondInfo = typeid( second );

It should not compile because typeid returns a reference to const.

Worse, you are asking for type info about the pointers. Both pointers are of type SomeCommonBase*, so you're guaranteed that they are of the same type. Ask instead for type info about the pointed to objects.

That said, as @DeadMg remarked, you also need to use operator== to compare type info objects.

The C++ standard does not address the issue of dynamic libraries. But within any given Windows module you should be safe.

Cheers & hth.,




回答2:


You can only retrieve const type_info references, and you should always use operator==.



来源:https://stackoverflow.com/questions/7024414/can-type-info-pointers-be-used-to-distingush-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!