Compression of the final fill space in the structure structure or inheritance

Consider the following code:

struct A { double d; float a; }; static_assert(sizeof(A) == 2 * sizeof(double), ""); struct B : A { float b; }; static_assert(sizeof(B) == sizeof(A), ""); //Fails struct C { A a; float b; }; static_assert(sizeof(C) == sizeof(A), ""); //Fails 

Is there a (preferably portable) way for b to live in an unused trailing space A?

I could change A by adding a catch-up data element at the end, or I could place-build b in the fill space, but there should be a better way to do this.

Perhaps the pragma package (but several data members A should remain aligned and not shrink)? Or are alignments correctly placed?

+7
c ++
source share
1 answer

Is an alternative approach available? Like this:

 struct A { char buf[100]; float *a() { return (float *)&buf[0]; } }; struct B : A { float *b() { return (float *)&buf[4]; } }; static_assert(sizeof(B) == sizeof(A), ""); // should pass 
0
source share

All Articles