I want to format a packet in an existing binary protocol format (I'm writing a memcached client) in C++. In C, I can do this:
typedef struct {
uint8_t magic;
uint8_t opcode;
uint16_t keylen;
uint8_t extlen;
uint8_t datatype;
uint16_t reserved;
uint32_t bodylen;
uint32_t opaque;
uint64_t cas;
} request_header;
In C++, in general, the compiler can add padding between the fields. However, the above struct is carefully laid out so that everything can be aligned with no padding, assuming n bit types only need to be aligned on n bit boundaries. So in C++, according to the standard, am I safe? Or could a conforming C++ compiler add extra padding, thwarting my ability to use this to lay out my bits?