Bright Leopold

i come from the other world,i will go back after the love,the regret,the alive and the dead are over

导航

struct 对齐和补齐原则

// 对齐原则:每一成员需对齐为后一成员类型的倍数

// 补齐原则:最终大小补齐为成员类型最大值的倍数
struct A
{
 int a;     // 4
 short b;   // (4) + 2 = 6 下一元素为 int,需对齐为 4 的倍数, 6 + (2) = 8
 int c;     // (8) + 4 = (12)
 char d;    // (12) + 1 = 13, 需补齐为 4 的倍数,13 + (3) = 16
};
struct B
{
 int a;     // 4
 short b;   // (4) + 2 = 6,下一成员为 char 类型,不考虑对齐
 char c;    // (6) + 1 = 7,下一成员为 int 类型,需对其为 4 的倍数,7 + (1) = 8
 int d;     // (8) + 4 = 12,已是 4 的倍数
}
所以sizeof(A)=16,sizeof(B)=12
 
2。不同的数据类型在32位和64位下所占字节的区别

32位编译器:

      char :1个字节
       char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节。同理64位编译器)
      short int : 2个字节
      int: 4个字节
      unsigned int : 4个字节
      float: 4个字节
      double: 8个字节
      long: 4个字节
      long long: 8个字节
      unsigned long: 4个字节

  64位编译器:

      char :1个字节
      char*(即指针变量): 8个字节
      short int : 2个字节
     int: 4个字节
      unsigned int : 4个字节
      float: 4个字节
      double: 8个字节
      long: 8个字节
      long long: 8个字节

      unsigned long: 8个字节
 
类的大小只与成员变量(非static数据成员变量)和虚函数指针有关,还要考虑到对齐.

posted on 2018-03-01 10:41  Bright Leopold  阅读(820)  评论(0编辑  收藏  举报