【发布时间】:2015-10-15 01:03:27
【问题描述】:
我正在阅读 Rust 书的lifetimes chapter,我遇到了这个命名/显式生命周期的示例:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
} // -+ x goes out of scope
我很清楚,编译器阻止的错误是分配给x 的引用的use-after-free:在内部范围完成后,f 和因此&f.x 变得无效,不应该被分配给x。
我的问题是这个问题可以很容易地被分析掉 没有 使用 explicit 'a 生命周期,例如通过推断非法分配对 a 的引用范围更广 (x = &f.x;)。
在哪些情况下实际上需要显式生命周期来防止 use-after-free(或其他一些类?)错误?
【问题讨论】:
-
对于这个问题的未来读者,请注意它链接到本书的第一版,现在有一个second edition :)
标签: reference rust static-analysis lifetime