rust - 是否有可能具有比其自身尺寸更大的对齐方式?

标签 rust alignment memory-layout

是否有可能在 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/

相关文章:

ios - 将 UIAlertAction 标题向左对齐

c++ - 虚函数和多重继承情况下的对象布局

c++ - 如何在结构中组织成员以在对齐时浪费最少的空间?

arrays - Rust向量(`Vec<T>`)与数组(`[T; n]`的性能

CSS - 保持列中的 div 对齐

macros - nom 的 "$i"宏参数从何而来?

html - 对齐侧边栏

struct - 为什么 sizeof::<Struct>() 不等于其字段大小的总和?

rust - 为什么我们需要在 Rust 中指定所有依赖项(包括传递项)?

xml - 如何使用 xml-rs 捕获一些值(如果可能的话)