by asuffield · 12y ago · 0 comments
TBH I don't find this to be that useful -- it covers up potential mistakes, and of course means that code breaks when compiled with the older version of OCaml which didn't do this.
Edit: I should note that this doesn't break type safety.
It has some unexpected properties: it can sometimes produce dangling pointers because it knows the target data will never be used, even though a GC would treat it as live. And on the other hand it will often promote data to an excessively long-lived region (because region lifetimes have to be nested). So current versions of the MLKit use GC as well as region inference.
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.