c++c++11memoryalignmentgranularity

alignment and word size


I'm confused by alignment requirement and word size. I'm working on a 64-bit processor, so the word size is 8, which means the allocated address should be a multiple of 8, right?
But alignof gives me unexpected results.

struct A
{
    int a;
    char b;
}

Output:

sizeof(A): 8
alignof(A): 4 // why?

In comparison,

sizeof(double): 8
alignof(double): 8

If I happen to provide an address that is a multiple of 4 but not a multiple of 8 for A, the performance will be lower because one more access, is that correct?

Is it because alignof() provides the least requirement that we need to follow, while alignment on 8 bytes in this specific example is better with a simple memory-performance trade-off?


Solution

  • The standard makes few guarantees with regard to alignment and general struct layout.

    Among them:

    Your example fulfills all of them. If you want, you can get a stronger alignment though (C++11):

    struct alignas(8) A {
        int a;
        char b;
    }
    

    Also, just because the bitness of the processor is 64, that is not reflected in higher alignment requirements for most types, though stronger-aligned data can have better read/write performance.

    You will only get worse performance if the weaker alignment means the data straddles more cache-lines and the processor must thus fetch more of them.