是否可以使用比其自身尺寸更大的对齐方式的类型?
Is it possible to have a type with a larger alignment than its own size?
有没有可能在 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);
}
也有类似的问题,答案似乎是 "not in standard C++, but some compiler extensions support it. You can't create an array of T in that case"。
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 中使用比其自身大小更大的对齐方式的类型?相反,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);
}
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.