by riffraff · 12y ago · 0 comments
But at the end of the day, the Rust compiler will never allow a reference to outlive the original object.
fn test_parse_unsafe() {
let v = {
let text = "The cat".to_string();
tokenize_string3(text.as_slice())
}; // `text` destroyed here
assert_eq!(vec![Word("The"), Other(" "), Word("cat")], v);
}
but the suggestion/question is about changing this to fn test_parse_unsafe() {
let v = {
let text = "The cat".to_string();
tokenize_string3(text.as_slice())
};
assert_eq!(vec![Word("The"), Other(" "), Word("cat")], v);
} // `text` destroyed here
so that the references in `v` are valid.This could lead to "memory leaks", where a destructor is implicitly postponed to a higher scope, but I don't think it would be much of a problem in practice (the promotion would only be through simple scopes, not through loops, and maybe not through `if`s). In fact, there's an yet-to-be-implemented accepted RFC covering this[1] (there's no guarantee that it will be implemented though, just that the idea is mostly sound).
[1]: https://github.com/rust-lang/rfcs/blob/master/active/0031-be...
I believe that it's safe to promote through an if, although obviously not through a general loop.