如果我在类上使用alignas,第一个成员或基类是否对齐?
如果我声明我的类 structalignas(16) C { int x; };,x
是否保证与 16 字节对齐,或者编译器可以将其填充到“左侧”吗? template
? Aligned
的 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”? What about template <typename T, std::size_t Align> struct alignas(Align) Aligned : T { using T::T; };
? Would the T
of Aligned<T, N>
be aligned to N
? Is that the right way to make a type that is a T
that is always aligned?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,
x
必须位于 16 字节边界上,因为您有一个 标准布局类。标准布局类保证类的第一个成员与类本身共享相同的地址,这意味着它将具有相同的对齐方式。只要
T
是标准布局类,情况就相同。如果是,则Aligned
具有标准布局,并且保证第一个基类子对象位于内存中对象的开头,因此它具有相同的对齐方式。这是一个办法。另一种方法是使用 std::aligned_storage 对象,然后使用placement new 将对象放置到该对齐存储中。
In this case,
x
has to be on the 16 byte boundary because you have a standard layout class. A standard layout class comes with a guarantee that the first member of the class shares the same address as the class itself, meaning it will have the same alignment.This is the same case as long as
T
is a standard layout class. If it is thenAligned
has standard layout, and the first base class subobject is guaranteed to be at the start of the object in memory, so it has the same alignment.It's an way. Another approach would be to use a
std::aligned_storage
object and then use placement new to emplace an object into that aligned storage.