What's the difference between sizeof and alignof?

后端 未结 7 1525
遥遥无期
遥遥无期 2020-12-23 17:19

What\'s the difference between sizeof and alignof?

#include 

#define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << \'/\' << a         


        
7条回答
  •  情歌与酒
    2020-12-23 17:49

    Old question (although not marked as answered..) but thought this example makes the difference a bit more explicit in addition to Christian Stieber's answer. Also Meluha's answer contains an error as sizeof(S) output is 16 not 12.

    // c has to occupy 8 bytes so that d (whose size is 8) starts on a 8 bytes boundary
    //            | 8 bytes |  | 8 bytes  |    | 8 bytes |
    struct Bad  {   char c;      double d;       int i;     }; 
    cout << alignof(Bad) << " " << sizeof(Bad) << endl;   // 8 24
    
    //             | 8 bytes |   |   8 bytes    |    
    struct Good {   double d;     int i; char c;          };
    cout << alignof(Good) << " " << sizeof(Good) << endl; // 8 16
    

    It also demonstrates that it is best ordering members by size with largest first (double in this case), as the others members are constrained by that member.

提交回复
热议问题