Is there a way to tell D to rearrange struct members or to not rearrange class members?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jun 28 03:53:38 UTC 2025


On Friday, June 27, 2025 1:55:30 PM Mountain Daylight Time WraithGlade via Digitalmars-d-learn wrote:
> Thanks for responding to my question and for your time, etc.
>
> I was aware of `align` but as far as I am aware it is orthogonal
> to what I'm asking about. The Andrei book says that D
> automatically rearranges members of `class`s in memory to avoid
> wasting memory due to padding between members whose width is less
> than the native CPU word size alignment, whereas `struct`s are
> left as is (meaning the members aren't reordered for alignment
> padding optimization).
>
> The `align` command specifies alignments but doesn't seem
> relevant to automatic rearranging of members for classes.
>
> I'm not sure if D does that or not anymore, since (as you said)
> it has been a long while since that book was published.

I don't know how much D does that with classes, but the implementation is
allowed to. It may do it all the time or not at all. I'd have to check.

As for structs, the compiler is not going to muck with their layout on its
own. You'll get padding based on the relative size of the fields, but the D
compiler is going to do what C does with the layout. The language doesn't
provide any mechanism to automatically rearrange the fields.

I have occasionally considered writing something to do it - probably either
a template mixin or a string mixin. You could write something where you gave
it a list of types and the names you wanted for the member variables, and
then it would order them however thy best fit to then be mixed into your
struct. However, that would have a compilation cost every time you built
that type, and it's rarely needed, so it's usually easier to just rearrange
the member variables in whatever the optimal order is. And in most cases,
personally, I don't care enough to bother figuring it out (though that's
also why I've considered writing something to at least tell me the optimal
order for space savings so that I can get an answer without having to think
about it).

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list