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

发布于 2025-01-15 10:46:45 字数 325 浏览 2 评论 0原文

如果我声明我的类 structalignas(16) C { int x; };,x 是否保证与 16 字节对齐,或者编译器可以将其填充到“左侧”吗? template怎么样? structalignas(Align) 对齐:T { 使用 T::T; };AlignedT 是否会与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟雨凡馨 2025-01-22 10:46:45

如果我声明我的类structalignas(16)C{intx; };x 是否保证与 16 字节对齐,或者编译器可以将其填充到“左侧”吗?

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

template怎么样? structalignas(Align) 对齐:T { 使用 T::T; };

只要 T 是标准布局类,情况就相同。如果是,则 Aligned 具有标准布局,并且保证第一个基类子对象位于内存中对象的开头,因此它具有相同的对齐方式。

这是创建始终对齐的 T 类型的正确方法吗?

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

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”?

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.

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

This is the same case as long as T is a standard layout class. If it is then Aligned 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.

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文