Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Substructure Bitfield Size

Tags:

c++

bit-fields

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.

like image 655
imallett Avatar asked Oct 22 '22 06:10

imallett


1 Answers

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.)

like image 131
Joe Z Avatar answered Dec 12 '22 08:12

Joe Z