首页 文章

如何分区和使用与Rust一起分配的堆内存?

提问于
浏览
5

我最近在Rust上读了很多,但我仍然只是开始氧化 . 我的大脑保留了大部分的C / C反应,所以请原谅我,如果这个问题不相关,因为Rust的工作方式如何 .

通常是否可能(希望?)在堆上分配任意大小的块,然后在其上映射数据结构,并使用较小块内存的绑定?

使用C99,人们可以这样写:

typedef unsigned char BYTE;

typedef struct {
    size_t size;
    BYTE payload[];
} flex;

// ...

flex * flex_new(size_t _size) {
    flex *f = malloc(sizeof(flex) + _size * sizeof(BYTE));
    f->size = _size;
    return f;
}

柔性长度阵列可能证明是有用的在使用可变大小的块实现内存池时,或者在专用于线程的堆上分配内存时 . 需要大小的数据结构仅在运行时已知,以“原子”方式分配,其成员连续打包 .

我想知道类似的Rust实现是否可行(没有 unsafe 构造),如果是,它看起来像什么 . 也许编译器可能会使用 struct 定义中的生命周期说明符来推断一些信息?

1 回答

  • 2

    就'flexible length arrays,'而言,您可以使用Vec::with_capacity来分配超出您的需求:

    let mut vec: Vec<int> = Vec::with_capacity(10);
    
    // The vector contains no items, even though it has capacity for more
    assert_eq!(vec.len(), 0);
    
    // These are all done without reallocating...
    for i in range(0i, 10) {
        vec.push(i);
    }
    
    // ...but this may make the vector reallocate
    vec.push(11);
    

    对于更一般的情况,TypedArena是您想要使用的 .

相关问题