Consider the following:
class A { public:
int gate_type : 4;
bool storage_elem : 1;
uint8_t privilege : 2;
bool present : 1;
} __attribute__((packed));
class B { public:
struct Sub {
int gate_type : 4;
bool storage_elem : 1;
uint8_t privilege : 2;
bool present : 1;
} type_attr; //Also tried with "__attribute__((packed))" here in addition to outside
} __attribute__((packed));
Compiler is g++ 4.8.1. sizeof(A)==1, sizeof(B)==4. Why is this so? I need something like structure B to have size 1.
This may seem like a dumb counter-question. I get the result you desire when I rewrite your example as:
class A { public:
int gate_type : 4;
bool storage_elem : 1;
uint8_t privilege : 2;
bool present : 1;
} __attribute__((packed));
class B { public:
A type_attr; //Also tried with "__attribute__((packed))" here in addition to outside
};
Is there some reason you can't reuse the definition of class A
inside of class B
? This really seems to be the better way to do it.
As I recall, neither C nor C++ guarantee that struct Sub
would have identical layout to and have identical storage requirements as class A
, despite having the same field widths, order and so on. (In C's case, it'd be struct Sub
vs. struct A
, but the same idea holds, since these are all POD types.)
The exact behavior ought to be ABI-dependent. By reusing class A
as I did above, though, I think you make yourself slightly more immune to ABI issues. (Slightly, not impervious.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With