c++memoryalignmentsizeofempty-class

Why c++ empty class have no byte alignment?


I recently learned that empty class have size 1 instead of zero.Why it has no byte alignment, in which it's size should be 4 in 32bit environment? What's the address of the next object?


Solution

  • Because C++ simply does not guarantee 4-byte alignment, or word-alignment, of variables. If this is important to you, you can specify an alignment requirement using alignas:

    struct alignas(4) my_empty_struct {};
    

    and now, the address of a my_empty_struct variable would be a multiple of 4 - and so will its size, apparently.

    Alternatively, you could pad your struct with a dummy field for alignment, yourself. The alignas is a bit like padding with an inaccessible field.