In the Visual Studio implementation of type_info, typically located in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\typeinfo:
class type_info {
/* ... */
_CRTIMP_PURE bool __CLR_OR_THIS_CALL operator==(const type_info& _Rhs) const;
/* ... */
private:
void *_M_data;
char _M_d_name[1];
__CLR_OR_THIS_CALL type_info(const type_info& _Rhs);
/* ... */
};
I noticed the implementation of the equality operator == uses the character pointer _M_d_name + 1. Can anyone explain to me how that "works", because it seems it would be out of the array bounds?
The implementation, C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\ti_inst.cpp:
ASSERT_UNMANAGED_CODE_ATTRIBUTE
SECURITYSAFECRITICAL_ATTRIBUTE
bool type_info::operator==(const type_info& rhs) const
{
return (strcmp((rhs._M_d_name)+1, (_M_d_name)+1)?0:1);
}
Thanks!
This trick is for the flexible array member. It will allocate memory for
class type_info
and the name string, so(rhs._M_d_name)+1
is exactly where the name string is. Here is a chart to describe it:Actually, c99 supports this feature and a Microsoft extension allows the last member of a C or C++ structure or class to be a variable-sized array