在哪里可以找到有关 C++ 的文档不同平台/编译器之间的内存对齐?

发布于 2024-12-03 02:11:18 字数 430 浏览 1 评论 0原文

我正在寻找关于 C++ 中的内存对齐、典型方法、编译器之间的差异以及常见陷阱的优秀(全面)文档。只是为了检查我对这个主题的理解是否正确并学习新的东西。

这个问题的灵感来自于我对另一个问题的回答,我使用了以下结构:

char const buf[1000] = ...;
unsigned int i = *reinterpret_cast<unsigned int*>(buf + shift); // shift can be anything

它被批评为不符合内存对齐规则。作为奖励,您能否解释一下为什么这种方法从内存对齐的角度来看存在缺陷?一个它不起作用的例子将受到高度赞赏。我知道这通常是一种不好的方法,但我经常在网络协议实现中使用它,所以这更多的是一个实际问题而不是理论问题。

另外请不要在这里提到严格别名,这是另一个问题。

I'm looking for a good (comprehensive) doc about memory alignment in C++, typical approaches, differences between compilers, and common pitfalls. Just to check if my understanding of the topic is correct and to learn something new.

This question is inspired by my answer to another question where I used following construct:

char const buf[1000] = ...;
unsigned int i = *reinterpret_cast<unsigned int*>(buf + shift); // shift can be anything

It was criticized as not conforming to memory alignment rules. Can you please explain as a bonus why this approach is flawed from memory alignment point of view? An example when it doesn't work will be highly appreciated. I know it's a bad approach in general, but I often use it in network protocol implementations, so it's more a practical question than theoretical one.

Also please don't mention strict-aliasing here, it's for another question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

厌倦 2024-12-10 02:11:18

非堆分配的 char 数组对其对齐方式没有特定要求。所以你的一千个字符的缓冲区可能有一个奇怪的偏移量。如果编译器没有将其拆分为单独的读取+,尝试从该偏移量(显然被重新解释为 int 指针)读取 int 会导致性能不佳,甚至在某些硬件上出现总线错误位掩码操作。

堆分配的 char 数组保证适当对齐以存储任何对象类型,因此这始终是一个选项。

对于基于非堆的存储,请使用 boost::aligned_storage 来确保空间正确对齐以供一般使用。

Non-heap-allocated arrays of char have no specific requirements on their alignment. So your buffer of a thousand characters could be on an odd offset. Trying to read an int from that offset (reinterpreted as an int pointer obvious) would either result in poor performance or even a bus error on some hardware if the compiler doesn't split it up into separate read+bitmask operations.

Heap-allocated arrays of char are guaranteed to be aligned suitably to store any object type, so this is always an option.

For non-heap based storage, use boost::aligned_storage which ensures that the space is aligned properly for general use.

长不大的小祸害 2024-12-10 02:11:18

您可以在 wikipedia 上找到概述。
更深入的内容请访问 IBM 网站:数据对齐:拉直并向右飞行

You can find an overview on wikipedia.
More in depth on the IBM site: Data alignment: Straighten up and fly right

滿滿的愛 2024-12-10 02:11:18

想象一下地址必须是 16 字节对齐的情况,例如 PS3。
然后想象shift == 1。
这肯定是一个非 16 字节对齐的指针,在本机上无法工作。

Imagine the case where addresses must be 16-byte aligned like for example the PS3.
And then imagine that the shift == 1.
This would then for sure be a non 16-byte aligned pointer which would not work on this machine.

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