Where can I find documentation on C++ memory alignment across different platforms/compilers?

后端 未结 3 845
星月不相逢
星月不相逢 2021-02-08 19:56

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 understand

3条回答
  •  情深已故
    2021-02-08 20:33

    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.

提交回复
热议问题