是否有可能在 Rust 中拥有比其自身尺寸更大的对齐方式?相反,rust 编译器是否总是向类型添加填充以使其大小至少是其对齐的倍数?
这个简单的示例代码似乎表明答案是否定的,所有类型的大小都是其对齐的倍数,但我想确保没有更多深奥的可能性。
use std::mem::{size_of, align_of};
struct b1 {
byte: u8
}
#[repr(align(4))]
struct b4 {
byte: u8
}
struct b5 {
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
}
#[repr(align(8))]
struct b8 {
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
}
fn main() {
assert_eq!(size_of::<b1>(), 1);
assert_eq!(align_of::<b1>(), 1);
assert_eq!(size_of::<b4>(), 4);
assert_eq!(align_of::<b4>(), 4);
assert_eq!(size_of::<b5>(), 5);
assert_eq!(align_of::<b5>(), 1);
assert_eq!(size_of::<b8>(), 8);
assert_eq!(align_of::<b8>(), 8);
}
C++ 也有类似的问题,其中的答案似乎是“不在标准 C++ 中,但某些编译器扩展支持它。在这种情况下,您无法创建 T 数组”。
最佳答案
Rust 引用文献中有关于大小和对齐的说明(重点是我的):
Size and Alignment
[...]
The size of a value is the offset in bytes between successive elements in an array with that item type including alignment padding. The size of a value is always a multiple of its alignment. The size of a value can be checked with the
size_of_val
function.
关于rust - 是否有可能具有比其自身尺寸更大的对齐方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61256701/