2

在以下结构中:

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

如何使用alignas这样sizeof(test)正好是 6 个字节?

alignas(1)编译器(gcc、msvc、clang)不接受(错误如:)error: requested alignment is less than minimum alignment of 4 for type 'test'

UPD。当然,此变体可以正常工作:

#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)

但是有没有办法在没有预处理器的情况下只使用标准 C++11/14 来做到这一点?

4

1 回答 1

3

alignas,只能让您使对齐更严格,并且只能达到标准类型的最大对齐。

该标准没有提供错位类型的机制。

于 2015-11-11T14:43:34.193 回答