I have this c++ structure:
struct Packet
{
uint32 MessageCount;
uint32 Length;
uint32 FieldValue;
union PacketHeader
{
uint32 typeInfo;
struct MagicVersion
{
uint8 MagicNumber[3];
uint8 Version;
};
};
Data * Payload(void) { return reinterpret_cast< Data * >(this + 1U); }
Data const * Payload(void) const { return reinterpret_cast< Data const * >(this + 1U); }
Packet * nextPacket(void) { return reinterpret_cast< Packet * >(this + 1U) + Length; }
Packet const * nextPacket(void) const { return reinterpret_cast< Packet const * >(this + 1U) + Length; }
};
Then sizeof(Packet)
in MSVC++ returns 12 instead of 16 which is what I expect.
The weird thing is of course that this is smaller that the expected value. Had it been bigger it could be because of alignment issues.
What am I missing?
TIA
Why do you think it should be bigger?
It contains 3 uint32
with no virtual methods, that's exactly 12 bytes.
The union doesn't count, since it's a type, it contains no member of that type.
If you want your class to contain a single instance of the union, which contains a single instance of the struct, you should write:
struct Packet
{
uint32 MessageCount;
uint32 Length;
uint32 FieldValue;
union
{
uint32 typeInfo;
struct
{
uint8 MagicNumber[3];
uint8 Version;
} /* MagicVersion */;
};
} /* PacketHeader */;
The names within /**/
are optional, you can either specify them or not. If you do, you have to access their members using the name of the union
/struct
, otherwise you'll have a flat Packet
struct.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments