3

Is the exact layout of D structs defined? That is, the exact offset of every member defined and in a compiler-independent way? That would mean that the compiler would, fortunately or unfortunately, depending on your needs, be forbidden to reorder fields to get optimal packing of smaller items and minimise all offsets.

Cecil Ward
  • 597
  • 2
  • 13

1 Answers1

5

It is indeed illegal for the D compiler to rearrange members of a struct (though it can for classes). It's important that the compiler not rearrange members for structs, because structs are supposed to be able to be used for low-level stuff that requires specific memory layouts. It's also the case that structs need to be able to interact with C code, so they need to match what you'd get it in C (at least when extern(C) is used). So, structs definitely don't get their members rearranged. In addition, you can specific the alignment of members via the align attribute, so you have full control over the layout of a struct.

Now, the default layout can differ depending on the architecture (e.g. 64-bit pointers take up more space than 32-bit pointers, which will affect how the struct members are packed), but it should match what you get in C on that architecture.

Jonathan M Davis
  • 37,181
  • 17
  • 72
  • 102
  • Does this imply that a D compiler for any architecture where improperly aligned data such as, odd addresses of words, are illegal (eg M68000, PDP-11?) would have to generate multiple single byte fetches or stores ? – Cecil Ward Aug 21 '16 at 00:05
  • @CecilWard AFAIK, no D compiler currently supports such an architecture, and while the official spec has lots of good information, it's still too often the case that what the reference compiler does is effectively the spec (and dmd is x86/x86_64 only). So, unless the issue has come up for gdc or ldc, it probably hasn't even been discussed. I expect that the answer is that the D compiler would do whatever the corresponding C compiler did, but I don't know. – Jonathan M Davis Aug 21 '16 at 02:25
  • Actually, I realise that you're absolutely right about the compatibility-with-C requirement, which you mentioned before of course. So actually my question was really a C question, and I don't know what C does, whether the various C or C++ standards have anything to say on the matter. The C compilers for 68000 that I used many years ago iirc would probably have refused to generate non-aligned words or would let the executable simply crash, but would not be kind enough to generate multiple byte fetches/stores. – Cecil Ward Aug 21 '16 at 02:36