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

Lance Bachmeier no at spam.net
Fri Jun 27 20:08:31 UTC 2025


On Friday, 27 June 2025 at 19:55:30 UTC, WraithGlade 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 think you're referring to [this description in the 
spec](https://dlang.org/spec/class.html#fields):

> The D compiler is free to rearrange the order of fields in a 
> class to optimally pack them. Consider the fields much like the 
> local variables in a function - the compiler assigns some to 
> registers and shuffles others around all to get the optimal 
> stack frame layout. This frees the code designer to organize 
> the fields in a manner that makes the code more readable rather 
> than being forced to organize it according to machine 
> optimization rules. Explicit control of field layout is 
> provided by struct/union types, not classes.


More information about the Digitalmars-d-learn mailing list