What's the difference between sizeof and alignof?

后端 未结 7 1553
遥遥无期
遥遥无期 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 18:04

    Well, "memory" is basically a huge array of bytes. However, most larger things like integers need more than 1 byte to store them -- a 32 bit value, for example, would use 4 consecutive bytes of memory.

    Now, the memory modules in your computer aren't usually "bytes"; they are also organized with a few bytes "in parallel", like blocks of 4 bytes.

    For a CPU, it's much easier = more efficient = better performance to not "cross" such block-borders when reading something like an integer:

    memory byte    0 1 2 3     4 5 6 7       8 9 10 11
     integer       goooood
                       baaaaaaaaad
    

    This is what the "alignment" says: an alignment of 4 means that data of this type should (or must, depends on the CPU) be stored starting at an address that is a multiple of 4.

    You observation that sizeof==alignof is incorrect; try structures. Structures will also be aligned (because their individual members need to end up on the correct addresses), but their size will be much larger.

提交回复
热议问题