Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use alignas to align struct

In the following struct:

struct alignas(?) test
{
    int32_t f1; // 4 bytes
    int8_t f2; // 1 byte
    int8_t f3; // 1 byte
};

How to use alignas so that sizeof(test) would be exactly 6 bytes?

alignas(1) is not accepted by compiler (gcc, msvc, clang) (error like: error: requested alignment is less than minimum alignment of 4 for type 'test').

UPD. This variant works OK, of course:

#pragma pack(push, 1)

struct alignas(?) test
{
    int32_t f1; // 4 bytes
    int8_t f2; // 1 byte
    int8_t f3; // 1 byte
};

#pragma pack(pop)

But is there a way to do it without preprocessor using only standard C++11/14?

like image 381
vladon Avatar asked Apr 28 '26 22:04

vladon


1 Answers

No. alignas only lets you make alignment stricter, and only up to the maximum alignment of standard types.

The standard provides no mechanism for misaligning types.

like image 53
rici Avatar answered Apr 30 '26 13:04

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!