7

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.

antoyo
  • 11,097
  • 7
  • 51
  • 82

1 Answers1

14

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.

  • 2
    Thanks for your answer. Do you know where is this documented? – antoyo Sep 13 '16 at 15:50
  • 3
    I don't really know, no more than I know where it's documented that GCC does not link a garbage collector into all programs. It's just... common knowledge, so to speak. –  Sep 13 '16 at 17:12
  • @antoyo: This is not documented as far as I know, however you can always check out the emitted LLVM IR (I find it more readable than the assembly). – Matthieu M. Sep 13 '16 at 19:33