Memory alignment : how to use alignof / alignas?

后端 未结 4 542
星月不相逢
星月不相逢 2020-12-02 05:43

I work with shared memory right now.

I can\'t understand alignof and alignas.

cppreference is unclear : alignof return

4条回答
  •  生来不讨喜
    2020-12-02 06:23

    Alignment is a property related with memory address. Simply we can say than if an address X is aligned to Z then x is a multiple of Z ,that is X = Zn+0. Here the important thing is Z is always a power of 2.

    Alignment is a property of a memory address, expressed as the numeric address modulo a power of 2. For example, the address 0x0001103F modulo 4 is 3. That address is said to be aligned to 4n+3, where 4 indicates the chosen power of 2. The alignment of an address depends on the chosen power of 2. The same address modulo 8 is 7. An address is said to be aligned to X if its alignment is Xn+0.

    The above statement is found on microsoft c++ reference .

    If a data item is stored in the memory with an address which is aligned to its size , then that data item is said to be naturally aligned , else misaligned. For eg : if an integer variable with size 4 bytes is stored in an address which is aligned to 4 , then we can say that the variable is naturally aligned , that is the address of the variable should be a multiple of 4.

    The compilers always tries to avoid misalignments . For simple datatypes the addresses are chosen such that it is a multiple of the size of the variable in bytes. The complier also pads suitably in the case of structures for natural alignment and access.Here the structure will be aligned to the maximum of the sizes of different data items in the structure.eg:

        struct abc
       {
            int a;
            char b;
       };
    

    Here the structure abc is aligned to 4 which is the size of int member which is obviously greater than 1 byte(size of char member).

    alignas

    This specifier is used to align user defined types like structure , class etc to a particular value which is a power of 2.

    alignof

    This is a kind of operator to get the value to which the structure or class type is aligned. eg:

    #include 
    struct alignas(16) Bar
    {
        int i; // 4 bytes
        int n; // 4 bytes
        short s; // 2 bytes
    };
    int main()
    {
        std::cout << alignof(Bar) << std::endl; // output: 16
    }
    

提交回复
热议问题