C++ - cstyle structure/class packing pertinent?

860 views Asked by At

Context

I primirarly code in C. Trying c++.

Not good enough with assembly to tell myself. But improving.

Questions

Do struct AND classes benefit from structure packing in c++ or is it only a c'ish thing?

Do c++ add lot of magic?

Will the private / protected / public segments mess all up?

Thanks

2

There are 2 answers

3
ravi On BEST ANSWER

First there are two different terms data structure alignment and data structure padding.

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

For your question "Do struct AND classes benefit from structure packing in c++"

Although C and C++ do not allow the compiler to reorder structure members to save space, other languages might. It is also possible to tell most C and C++ compilers to "pack" the members of a structure to a certain level of alignment, e.g. "pack(2)" means align data members larger than a byte to a two-byte boundary so that any padding members are at most one byte long.

By changing the ordering of members in a structure, it is possible to change the amount of padding required to maintain alignment. For example, if members are sorted by descending alignment requirements a minimal amount of padding is required which means arranging elements in struct with largest at the beginning.

0
Goswin von Brederlow On

C++ struct is 100% backward compatible to C struct. All the same rules apply. And class is just a struct where the default is private instead of public. So the same rules still apply. You get all members of struct/class in the order specified with the normal C alignment and padding rules applied.

But don't go and tell the compiler to pack your struct or class. The extra padding the compiler normaly inserts means that the members can be accessed faster. Packed structures require more cpu time to access members (on x86/amd64 mostly) or more complex code to do unaligned access (pretty much every other cpu).

Only good reason for packed structures is for storing struct in files or transmitting them over the net where different alignment and padding rules of different systems would cause incompatibility. If you need that then pack the data into the packed struct as late as possible before savin/sending and unpack it into a not packed struct as soon as possible after reading/receiving. You can do endian conversion at the same time.