Why class size increases when int64_t changes to int32_t

前端 未结 4 565
北荒
北荒 2021-02-11 19:47

In my first example I have two bitfields using int64_t. When I compile and get the size of the class I get 8.

class Test
{
    int64_t first : 40;
         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-11 20:27

    Standard says:

    § 9.6 bit-fields

    Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. [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. — end note]

    c++11 paper

    So layout depends on compiler implementation, compilation flags, target arch and so on. Just checked several compilers and output mostly is 8 8:

    #include 
    #include 
    
    class Test32
    {
        int64_t first : 40;
        int32_t second : 24;
    };
    
    class Test64
    {
        int64_t first : 40;
        int64_t second : 24;
    };
    
    int main()
    {
        std::cout << sizeof(Test32) << " " << sizeof(Test64);
    }
    

提交回复
热议问题