Why c++ empty class have no byte alignment?

156 views Asked by At

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?

1

There are 1 answers

3
einpoklum On BEST ANSWER

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.