fn dangle() {
fn get_str<'a>(s: *const String) -> &'a str {
unsafe { &*s }
}
let s = String::from("hello");
let dangling = get_str(&s);
drop(s);
println!("Invalid str: {}", dangling);
}
#[test]
fn test() {
dangle(); // it should panic, but does not
}
fn main() {
dangle(); // panics
}
main()
正如我所料,该函数崩溃了。但为什么该test()
函数能够成功运行?