-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Documentation of std::mem::size_of confusingly only details the #[repr(C)]
case
#55115
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
#[repr(C)]
case
You're misreading the documentation. The Size of Structs paragraph is a sub-heading of the "Size of #[repr(C)] items" section. But the difference in heading size makes it easy to miss that fact. |
Thanks for pointing this out. Goes to show that the docs could be improved. It'd be nice to get paragraphs for other |
I wonder if this text should just be moved into the unsafe guidelines instead? Are there any cases in safe code where the exact layout matters for correctness (not just performance)? |
Well I don't think that having all the possible memory layouts detailed on the |
@scottmcm Pointer shenanigans and transmutes. FWIW, this information does exist on the reference, though IMO, it almost makes sense to document here since they're the explanation of the output of why the output of the function is what it says. |
We could maybe try to make the size of structs a bit more verbose by changing:
And then adding to the introduction of the sizeof operator a small paragraph stating that the ordering of fields is not defined by the default Rust representation (not sure if this has a name?), and that the compiler is allows to reorder the fields and apply padding as it sees fit. Or instead of only editing the introduction we could introduce a new section for Rust's default representation. I can create a PR if there isn't anyone else that wants to pick this up! |
The Size of Structs paragraph bases its explanation of struct sizes on the idea that field are "ordered by declaration order", which is no longer the case since #37429 got merged. This might prompt a user to pointlessly manually order fields to optimize for size.
Instead, the documentation should mention the issue of field alignments, and explain that the compiler will reorder fields to minimize padding. The exact algorithm might be a bit too complex and/or subject to change, so I don't think that it needs to be described completely. It's probably enough to say something like "the compiler reorders fields for optimisation, don't expect a particular order unless using one of the
repr
specifier".The text was updated successfully, but these errors were encountered: