Given the following function definitions:
// A: Compiles with static lifetime
fn foo() -> &'static i32 {
let i = &42;
i
}
// B: Compiles with normal lifetime
fn bar<'a>() -> &'a i32 {
let i = &42;
i
}
// C: Does not compile but same as B
fn baz<'a>() -> &'a i32 {
let i = 42;
&i
}
// D: Does not compile either
fn qux() -> &i32 {
let i = &42;
i
}
I would expect all 4 of these to fail compilation because we are returning a reference to a local variable but to my surprise A and B both compile correctly, yet C and D do not.
For A: How is it possible to use 'static
here because static data lives for the lifetime of the program and this data is created dynamically (possibly multiple times) during program execution?
For B: Why is this allowed and what is the lifetime of 'a
bound to - is it implicitly 'static
as well? Why does this no longer work when changing to types such as String
?
For C and D: Why do these not compile when they are effectively identical to B?
Do any of these create dangling pointers, or is something going on behind the scenes?
Do they create memory leaks because the returned value lives forever?