Struct padding in C++

后端 未结 4 979
误落风尘
误落风尘 2020-11-22 09:11

If I have a struct in C++, is there no way to safely read/write it to a file that is cross-platform/compiler compatible?

Because if I understand correct

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 09:54

    Long story short, no. There is no platform-independent, Standard-conformant way to deal with padding.

    Padding is called "alignment" in the Standard, and it begins discussing it in 3.9/5:

    Object types have alignment requirements (3.9.1, 3.9.2). The alignment of a complete object type is an implementation-defined integer value representing a number of bytes; an object is allocated at an address that meets the alignment requirements of its object type.

    But it goes on from there and winds off to many dark corners of the Standard. Alignment is "implementation-defined" meaning it can be different across different compilers, or even across address models (ie 32-bit/64-bit) under the same compiler.

    Unless you have truly harsh performance requirements, you might consider storing your data to disc in a different format, like char strings. Many high-performance protocols send everything using strings when the natural format might be something else. For example, a low-latency exchange feed I recently worked on sends dates as strings formatted like this: "20110321" and times are sent similarly: "141055.200". Even though this exchange feed sends 5 million messages per second all day long, they still use strings for everything because that way they can avoid endian-ness and other issues.

提交回复
热议问题