These structs, align1
and align2
, contain the same data, but align1
has more padding due to the nested layout.
How can I get the memory saving alignment of align2
while also using a nested struct like in align1
?
int main() {
struct align1 {
struct {
double d; // 8 bytes
bool b1; //+1 byte (+ 7 bytes padding) = 16 bytes
} subStruct;
bool b2; //+1 byte (+ 7 bytes padding) = 24 bytes
};
struct align2 {
double d; // 8 bytes
bool b1, b2; //+2 byte (+ 6 bytes padding) = 16 bytes
};
std::cout << "align1: " << sizeof(align1) << " bytes\n"; // 24 bytes
std::cout << "align2: " << sizeof(align2) << " bytes\n"; // 16 bytes
return 0;
}
The nested subStruct
struct is needed since it is going to be declared/defined outside. I'm using C++17 and Visual Studio 2017.
The resulting code can be as dirty or bad looking as hell. I just don't want it to throw random errors at me later on or break when changing the configuration.