-
Notifications
You must be signed in to change notification settings - Fork 59
'static
reference to local variable that never goes out of scope?
#565
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Lifetimes at the language level don't participate in the operational semantics, they only determines what code is well-formed. Note that you'll also need to make sure that |
Ah good point. |
Okay, do you think this is sound? pub fn with_static<T: 'static, F: FnOnce(&'static mut T)>(t: T, f: F) -> ! {
struct AbortOnDrop<T>(T);
impl<T> Drop for AbortOnDrop<T> {
fn drop(&mut self) {
loop {}
}
}
let mut t = AbortOnDrop(t);
let tp: *mut T = &mut t.0;
// SAFETY: Since we `drop(t)` after the `loop {}`, `t` will only go out of
// scope if `f` unwinds. If this happens, `AbortOnDrop::drop` will `loop {}`
// forever before its inner `T` is destructed. Thus, `t.0` will never be
// destructed, and so it is sound to synthesize a `'static` reference to
// `t`.
f(unsafe { &mut *tp });
loop {}
drop(t);
} |
if that drop works like how you seem to think it does, then you don't need to write the loop and drop call after the unsafe function call |
I wouldn't hold the In any case, from an opsem perspective, as mentioned, it's perfectly fine to "lie" about lifetimes, as long as you don't use the reference after the reference is invalidated (which happens when the storage is deallocated, probably on move, and definitely on a conflicting write). As I mentioned, the lifetimes don't exist at runtime, they're just static guides that make it so that things that aren't valid at runtime aren't valid at compile time. |
Interesting. I was assuming that the invalidation would happen after |
The move will probably invalidate it. |
What guarantees are provided regarding drop order in the presence of unwinding? Is that something I could rely on? |
I think drops have to be "bottom of the block upwards" regardless of if it's an unwind or a normal return. Otherwise you can trivially make situations that don't make sense. |
Yes. We even have a proof of that in RustBelt. :D You can even take in the I would just remove the field from |
Is the following sound? In particular, is it sound to synthesize a
'static
reference to a local variable if we can prove that that variable will never go out of scope at runtime because the local scope will never finish executing?The text was updated successfully, but these errors were encountered: