lundi 7 septembre 2020

C++ alignas(1) does not affect the size of a struct

Consider the code below:

#include <iostream>

struct alignas(1) H1 {
    uint8_t f8;
    uint64_t f64;
};

#pragma pack(push, 1)
struct H3 {
    uint8_t f8;
    uint64_t f64;
};
#pragma pack(pop)

int main() {
    std::cout << "H1 " << sizeof(H1) << std::endl;
    std::cout << "H3 " << sizeof(H3) << std::endl;
    return 0;
}

The output:

$ ./a.out
H1 16
H3 9

The alignas(1) did not affect the size of H1 while #pragma did. On the contrary, alignas(64) actually increases the size of a struct.

Aucun commentaire:

Enregistrer un commentaire