Why does the reference to local variable return successfully?

Viewed 48

call1 and call2 fails to compile as expected. But call3 compiles rather than throws an error like "cannot return reference to temporary value". Why?

struct Demo(i32);

impl Demo {
    fn new() -> Self {
        Self(22)
    }
}

// Compile error: cannot return reference to temporary value
fn call1<'a>() -> &'a Demo {
    let a = Demo(3);
    &a
}

// Compile error: cannot return reference to temporary value
fn call2<'a>() -> &'a Demo{
    &Demo::new()
}

// Compiles!
fn call3<'a>() -> &'a Demo {
    &Demo(34)
}
0 Answers
Related