c++ - Are nested structs the same size as flattened structs? -


#include <iostream> #include <string>  struct { int x; }; struct b { a; char y; }; struct c { b b; double z; }; struct d { c c; void *alpha; }; struct e { d d; float beta; };  struct f {     int x; char y; double z; void *alpha; float beta; };  int main() {     static_assert(sizeof(e) == sizeof(f), "whoops!"); } 

the above works , gives me same sizes. i'd prefer guarantee true. it?

no, need not same. sizes of 2 alternatives need not different either, depend on situation, joachim mentions in comments padding play role. focusing on simpler types, standard-layout (and in example pod, more restrictive):

struct { int a; };         // 4 aligned, size 4 struct b { a; char ch; };  // 4 aligned, size 8 struct c { b b; char ch2; }; // 4 aligned, size 12 

the reason that, provide right alignment int member in b, compiler (not mandated, compilers aim have natural alignment) injects 3 bytes of padding after ch member. when b used inside c, requires 8 bytes (including 3 of padding), after adding ch2 compiler injects additional padding , ends wasting total of 6 bytes.

struct d { int a; char ch; char ch2; }; 

in case, natural alignment of ch , ch2 1, there no padding between 2 members. there padding @ end of structure (in case 2 bytes) there less total padding.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -