我怎样才能延迟Rust的内存自动管理?

div*_*tes 1 memory-management rust

Rust开发了一个聪明的内存管理系统,但我有以下情况:

loop {
    let mut example = Very_Complicated_Struct::new();
    // very complicated data structure created

    dealing_with(&mut example);
}
// End of scope, so Rust is supposed to automatically drop the
// memory of example here, which is time consuming

time_demanding_steps();

// But I want Rust to drop memory here,
// after the time_demanding_steps()
Run Code Online (Sandbox Code Playgroud)

Rust有办法这么做吗?

She*_*ter 6

使用a TypedArena也可能是一种解决方案.

let arena = Arena::new()

loop {
    let example = arena.alloc(Very_Complicated_Struct::new());
    dealing_with(example);
}

time_demanding_steps();

// Arena and all contained values are dropped
Run Code Online (Sandbox Code Playgroud)

您必须遵守一些限制,特别是您不会直接拥有该结构; 你只得到一个&mut T.

这是Matthieu M.描述的"垃圾架"模式的专门案例.