Home  >  Q&A  >  body text

c++ - 一个类的大小

class A
{
    double a;
    short b;
    int c;
    char d;
}

请问sizeof(A)的大小是多少?对齐的原则是什么

ringa_leeringa_lee2764 days ago793

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 12:04:23

    sizeof(A)==24

    double a: sizeof(double) == 8
    short b originally occupies 2, because later int c occupies 4, it needs to be aligned with c, b also becomes 4, (b and c add up to exactly 4 8, just aligned with the longest double a)
    char d is aligned with the largest double a, occupying 8.

    So after understanding some principles of alignment, you can save space by adjusting the declaration order of members, such as changing A to:
    class A
    {

    double a;
    char d;
    short b;
    int c;

    };
    sizeof(A) == 16, because
    d is aligned with b, accounting for 2, and d(2) + b(2) + c(4) is exactly 8, aligned with a, So it occupies exactly 16, which is 8 less for the former definition.

    Regarding the principle of "data structure alignment", it cannot be explained clearly in a few words. You can search for "C Data structure alignment" or "C Data structure padding" and there will be a lot of articles.

    Additional explanation:
    The above is the alignment method under normal circumstances (that is, without modifying the compiler's compilation behavior), but you can also tell the compiler how many bytes to use for alignment, such as in the A statement Add a sentence in front:

    #pragma pack(4)

    This will cause the compiler to align with 4 bytes instead of the longest member in the structure (double a). If it is aligned with 4 bytes, sizeof(A) == 20.

    For the gcc compiler, you can also use

    __attribute((aligned (n)))

    to set n-byte alignment.

    If these two settings are not turned on on the machine where your original question is located, then your compiler may use 4-byte alignment by default. Please verify it.

    Reference link:
    http://www.cnblogs.com/graphics/archive/2010/08/12/1797953.html
    http://blog.csdn.net/edonlii/article/details /12748903

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:04:23

    The alignment methods of different compilation environments are slightly different. The commonly used rule in g++ is that the member offset must be divided by its own size. Double size 8, offset 0 is no problem, short size 2, offset 8, int size 4, if offset 10 is wrong, so the offset of c is 12, and then the short size 1 is offset by 16, so the total is 17 bytes. Considering that a 32-bit machine processes 4 bytes at a time, 3 bytes are added to make 20 Bytes are multiples of 4. It is estimated that 64-bit is 24 bytes in multiples of 8. The claw machine has not been tested

    reply
    0
  • Cancelreply