简体   繁体   中英

Is Rust using region-based memory management?

For instance, if we forget about return value optimization, and have the following code:

fn func() -> Box<String> {
    Box::new(String::new())
}

fn main() {
    let boxed_string = func();
}

will the compiler create regions to manage the memory or will it use normal heap allocation?

I know this simple code might be optimized, but in a more complex code, it might not be the case.

While lifetimes can arguably be called "regions" in the same sense as in region-based memory management, Rust does not automatically manage memory based on them. Lifetimes are only used for static analysis. Memory is allocated in the normal ways — registers, stack, heap (some C-style malloc function), possible other abstractions like memory pools if manually implemented as in the typed-arena crate. This perfectly ordinary memory management is then analyzed by the compiler, using the concept of regions, but that doesn't affect the run time behavior at all. In fact, lifetimes are erased from the program before the machine code is even generated.

However, there might be additional moves in your code. Box::new is an ordinary function into which the argument is moved, and likewise String::new 's return might involve a move.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM