Why is the “alignment” the same on 32-bit and 64-bit systems?

后端 未结 4 1441
暗喜
暗喜 2021-02-19 00:16

I was wondering whether the compiler would use different padding on 32-bit and 64-bit systems, so I wrote the code below in a simple VS2019 C++ console project:

         


        
4条回答
  •  甜味超标
    2021-02-19 00:59

    A struct's alignment is the size of its largest member.

    That means if you have an 8-byte(64bit) member in the struct, then the struct will align to 8 bytes.

    In the case that you are describing, if the compiler allows the struct to align to 4 bytes, it possibly leads to an 8-byte member lying across the cache line boundary.


    Say we have a CPU that has a 16-byte cache line. Consider a struct like this:

    struct Z
    {
        char s;      // 1-4 byte
        __int64 i;   // 5-12 byte
        __int64 i2;  // 13-20 byte, need two cache line fetches to read this variable
    };
    

提交回复
热议问题