C++ bitfield packing with bools

前端 未结 6 1303
北恋
北恋 2020-12-05 04:19

I\'ve just done a test with bitfields, and the results are surprising me.

class test1 {
public:
    bool test_a:1;
    bool test_b:1;
    bool test_c:1;
            


        
6条回答
  •  甜味超标
    2020-12-05 05:12

    Be careful with bitfields as much of its behavior is implementation (compiler) defined:

    From C++03, 9.6 Bitfields (pg. 163):

    Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit. [Note:bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others. ]

    That is, it is not a bug in the compiler but rather lack of a standard definition of how it should behave.

提交回复
热议问题