如果我在 class 上使用 alignas,第一个成员或基数 class 是否对齐?

If I use alignas on a class, is the first member or base class aligned?

如果我声明我的 class struct alignas(16) C { int x; };x 是否保证与 16 字节对齐,或者编译器可以将其填充到“左侧”? template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; }; 呢? Aligned<T, N>T 会与 N 对齐吗?这是制作始终对齐的 T 类型的正确方法吗?

If I declare my class struct alignas(16) C { int x; };, is x guaranteed to be aligned to 16 bytes or could the compiler pad it on the “left”?

在这种情况下,x 必须位于 16 字节边界上,因为您有一个 standard layout class。标准布局 class 保证 class 的第一个成员与 class 本身共享相同的地址,这意味着它将具有相同的对齐方式。

What about template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; };?

只要T是标准布局class,这个都是一样的。如果是,则 Aligned 具有标准布局,第一个基础 class 子对象保证位于内存中对象的开头,因此它具有相同的对齐方式。

Is that the right way to make a type that is a T that is always aligned?

这是一种方式。另一种方法是使用 std::aligned_storage 对象,然后使用 placement new 将对象放置到对齐的存储中。