Is there anything in the C++ standard preventing a compiler from packing its fields so that one field may overlap with the padding of another?
It's allowed when inheriting (possibly via the empty base class optimization). To illustrate the scenario, consider the following snippet:
#include <cstdint> #include <cstdlib> struct A { A() { a2 = rand(); } // force non-POD uint32_t a1; uint16_t a2; }; struct B { A b1; uint16_t b2; }; struct C : A { uint16_t c; }; B and C contain the same fields, but C will only occupy 8 bytes, whereas B will have padding inserted before b2.
I've tested this both with clang (Apple LLVM version 5.0) and GCC 4.7.3, they both behave the same, and produces the following layout:
struct A [8 Bytes] 0: [uint32_t : 4] a1 4: [uint16_t : 2] a2 --- 2 Bytes padding --- struct B [12 Bytes] 0: [uint32_t : 4] b1.a1 4: [uint16_t : 2] b1.a2 --- 2 Bytes padding --- 8: [uint16_t : 2] b2 --- 2 Bytes padding --- struct C [8 Bytes] 0: [uint32_t : 4] A::a1 4: [uint16_t : 2] A::a2 6: [uint16_t : 2] c (If A is made a POD, both B and C will have padding, presumably because offsetof() is allowed and the optimization would become visible and possibly break code).
I'm curious, is there's a good reason for not packing the fields optimally in the B case?
reason for not packing the fields optimallyoptimally by which criteria?stdwithout “std::” qualification nor using-declarations / using-directive; I guess that on your implementation<cxxx>happens to include<xxx.h>but that's not guaranteed.)