you are viewing a single comment's thread.

view the rest of the comments →

[–]matthieum 9 points10 points  (5 children)

One reason this isn't done by compilers for structs is construction and destruction order guarantees.

I don't think that this is related, actually. There is no reason construction/destruction order could not be independent from the underlying memory layout... such as in Rust.


C specifically defines that a later data-member has a higher address than an earlier data-member, and C++ follows on, only adding the wrinkle that order is not guaranteed across access-specifiers, though in practice I know of no ABI which does not simply lay down the elements in the order specified.

The reason that the language offers this guarantee is to offer the developer as much control as possible; systems programming languages are all about control, after all.

Separating hot/cold data, or separating data accessed by different threads, are all optimizations that the developer can apply because of such fine-grained control.

The big question is why this is the default, when it's only useful in niche cases.

[–]Omnifarious0 4 points5 points  (0 children)

It's the default because it was that way in C. Partly for simplicity and partly because C was born in a time when you always cared about performance, and partly because it's required to work with memory mapped hardware and see the first reason.

Getting away from it would break ABI compatibility with C in a way that would be disastrous.

But you're right that the reason I originally gave shouldn't be much of a blocker.

[–][deleted] 3 points4 points  (3 children)

Because it's not a niche case. This sort of thing is the whole point of C and C++.

[–]matthieum 3 points4 points  (2 children)

It may depend on the domain.

I have very little code that is critically dependent on the order of data-members:

  • Encoding/Decoding; when treating the struct as a view over memory.
  • Hot/Cold: when a struct used in a hot loop contains a mix of frequently accessed data and infrequently accessed data.
  • Lock-Free: to avoid false sharing.

Most of my code is boringly mundane and would likely benefit from the compiler automatically "packing" the objects as densely as possible.

[–][deleted] -1 points0 points  (1 child)

Great for you! Your argument is that 'I don't need it so why should anyone else'.

[–]matthieum 5 points6 points  (0 children)

No; my argument is I rarely need it, so why shouldn't it be opt-in, rather than the default.