I'm micro-optimizing code for identifying object types. I assume I can use the following for checking whether two objects instantiated in the same module have identical types:
SomeCommonBase& first = ...;
SomeCommonBase& second = ...;
const type_info& firstInfo = typeid( first );
const type_info& secondInfo = typeid( second );
if( &firstInfo == &secondInfo || firstInfo == secondInfo ) {
//identical types
} else {
//different types
}
The logic is that once a type_info
reference is returned the object behind that reference is guaranteed to live until the module is unloaded. So once a reference is returned no other object can occupy the same address.
开发者_StackOverflow中文版So if addresses match then those are identical type_info
objects and identical data types. If the implementation returns different type_info
objects for the same type type_info::operator==
is invoked and does additional check.
Is that a correct assumption?
Obviously.
Equal addresses mean that both pointers refer to the same object in memory. If the pointer is of type type_info*
, then obviously it means the objects (i.e first
and second
in your case) passed to typeid()
are of same type. After all, how can two pointers having same address, might refer to the different type_info
objects, so as to become different type?
精彩评论