How to use alignas to replace pragma pack?

alignas cannot replace #pragma pack.

GCC accepts the alignas declaration, but still keeps the member properly aligned: satisfying the strictest alignment requirement (in this case, the alignment of long) also satisfies the requirement you specified.

However, GCC is too lenient as the standard actually explicitly forbids this in §7.6.2, paragraph 5:

The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers were omitted (including those in other declarations).


I suppose you know that working with unaligned or missaligned data have risks and have costs.

For instance, retrieving a missaligned Data Structure of 5 bytes is more time-expensive than retrieving an 8 bytes aligned one. This is because, if your 5 "... byte data does not start on one of those 4 byte boundaries, the computer must read the memory twice, and then assemble the 4 bytes to a single register internally" (1).

Working with unaligned data requires more mathematical operations and ends in more time (and power) consumption by the ECU.

Please, consider that both C and C++ are conceived to be "hardware friendly" languages, which means not only "minimum memory usage" languages, but principally languages focused on efficiency and fastness processing. Data alignmnt (when it is not strictly required for "what I need to store") is a concept that implies another one: "many times, software and hardware are similar to life: you require sacrifices to reach better results!".

Please, consider also asking yourself is you do not have a wrong assumption. Something like: "smaller/st structures => faster/st processing". If this were the case, you might be (totally) wrong.

But if we suppose that your point is something like this: you do not care at all about efficiency, power consumption and fastness of your software, but just you are obsessed (because of your hardware limitations or just because of theoritcal interest) in "minimum memory usage", then and perhaps you might find useful the following readings:

(1) Declare, manipulate and access unaligned memory in C++

(2) C Avoiding Alignment Issues

BUT, please, be sure to read the following ones:

(3) What does the standard say about unaligned memory access?

Which redirects to this Standard's snipped:

(4) http://eel.is/c++draft/basic.life#1

(5) Unaligned memory access: is it defined behavior or not? [Which is duplicated but, maybe, with some extra information].


Unfortunately, alignment is not guaranted, neither in C++11 nor in C++14. But it is effectived guaranted in C++17.

Please, check this excellent work from Bartlomiej Filipek:

https://www.bfilipek.com/2019/08/newnew-align.html