Regarding structure padding in c++

后端 未结 4 436
猫巷女王i
猫巷女王i 2021-01-16 05:50

I use a datastructure in my project and in the context of a paricular structure i have a doubt about strucure padding. First Look at the strucure given below. I use Visual S

4条回答
  •  悲哀的现实
    2021-01-16 06:09

    While all the answers saying that it's up to the compiler are correct, because it is up to the compiler, the language specification places some limitations on the layout. These restrictions apply to all structures in C, "plain old data" in C++03 (which basically means only using features from C) and "standard-layout" structures in C++11 (which allows having constructor and destructor). The restrictions are:

    • (Reinterpret-)casting pointer to the structure to the type of the first member produces valid pointer to the first member (C++11 §9.2/20). Which implies there can't be padding before first member.
    • If two structures in a union have the same initial part (members of the same type in the same order) and the union is initialized via one of them, these initial members may be accessed via the other (C++11 §9.2/19). Which means the member offset may only depend on members declared before it.

    The restriction to standard layout is important. Neither holds for classes that have base classes or virtual members.

    Now when combined with the desire not to waste memory, this actually leaves only one practical algorithm, that is therefore used by all compilers. Which does not mean that all compilers will produce the same layout for the same input, because the sizes and alignment requirements for various primitive types differ between platforms. The algorithm is:

    • Lay out the first member at offset 0.
    • Lay out each following member at first available offset divisible by it's required alignment.
    • Round the size of the structure up to the next multiple of largest alignment of any member.
    • Alignment requirement of the structure is the largest alignment of any member.

    (I am almost certain MSDN for MSVC++ describes this somewhere, but couldn't quickly find it)

提交回复
热议问题