type_info 指针可以用来区分 C++ 中的类型吗?
我有一组多态 C++ 类,它们都由同一模块(Windows DLL)实例化。现在有两个指向此类的指针并调用了 typeid
:
SomeCommonBase* first = ...; //valid pointer
SomeCommonBase* second = ...; //valid pointer
const type_info& firstInfo = typeid( first );
const type_info& secondInfo = typeid( second );
我可以比较检索到的 type_info
地址
if( &firstInfo == &secondInfo ) {
//objects are of the same class
} else {
//objects are of different classes
}
或使用 ==
if( firstInfo == secondInfo ) {
//objects are of the same class
} else {
//objects are of different classes
}
来检测对象是否属于 (完全一样)同一类还是不同类?当从同一模块内实例化对象时,是否保证可以工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我写这篇文章时,您的代码
不应该编译,因为
typeid
返回对const
的引用。更糟糕的是,您需要有关指针的类型信息。两个指针的类型均为
SomeCommonBase*
,因此可以保证它们具有相同的类型。相反,询问有关所指向对象的类型信息。也就是说,正如 @DeadMg 所说,您还需要使用
operator==
来比较类型信息对象。C++ 标准没有解决动态库的问题。但在任何给定的 Windows 模块中,您都应该是安全的。
干杯&呵呵,
As I'm writing this, your code is
It should not compile because
typeid
returns a reference toconst
.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.,
您只能检索
const
type_info 引用,并且应始终使用operator==
。You can only retrieve
const
type_info references, and you should always useoperator==
.