Is there any environment where “int” would cause struct padding?

后端 未结 5 1186
再見小時候
再見小時候 2021-01-07 18:30

Specifically, this came up in a discussion:

Memory consuption wise, is there a possibility that using a struct of two ints t

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 18:58

    Is there any reasonable (not necessarily common or current) environment where this small program would print bigger?

    Not that I know of. I know that's not completely reassuring, but I have reason to believe there is no such environment due to the requirements imposed by the C++ standard.

    In a standard-compliant† compiler the following hold:

    • (1) arrays cannot have any padding between elements, due to the way they can be accessed with pointersref;
    • (2) standard layout structs may or may not have padding after each member, but not at the beginning, because they are layout-compatible with "shorter"-but-equal standard layout structsref;
    • (3) array elements and struct members are properly alignedref;

    From (1) and (3), it follows that the alignment of a type is less than or equal to its size. Were it greater, an array would need to add padding to have all its elements aligned. For the same reason, the size of a type is always a whole multiple of its alignment.

    This means that in a struct as the one given, the second member will always be properly aligned—whatever the size and alignment of ints—if placed right after the first member, i.e., no interstitial padding is required. Under this layout, the size of the struct is also already a multiple of its alignment, so no trailing padding is required either.

    There is no standard-compliant set of (size, alignment) values that we can pick that makes this structure need any form of padding.

    Any such padding would then need a different purpose. However, such a purpose seems elusive. Suppose there is an environment that needs this padding for some reason. Whatever the reason for the padding is, it would likely‡ also apply in the case of arrays, but from (1) we know that it cannot.

    But suppose such an environment truly exists and we want a C++ compiler for it. It could support this extra required padding in arrays by simply making ints larger that much, i.e. by putting the padding inside the ints. This would in turn once more allow the struct to be the same size as two ints and leave us without a reason to add padding.


    † A compiler—even one otherwise not-standard-compliant—that gets any of these wrong is arguably buggy, so I'll ignore those.

    ‡ I guess that in an environment where arrays and structures are primitives there might be some underlying distinction that allows us to have unpadded arrays and padded structs, but again, I don't know of any such thing in use.

提交回复
热议问题