struct’s lifetime necessities might be bypassed by way of covariant subject project · Issue #164250 · rust-lang/rust · GitHub


In the next code:

use std::sync::Mutex;
static KEPT: Mutex<Vec<Box<dyn std::any::Any + Send>>> = Mutex::new(Vec::new());
struct Q<T: 'static + Send>(Option<T>);
impl<T: 'static + Send> Drop for Q<T> {
    fn drop(&mut self) { if let Some(t) = self.0.take() { KEPT.lock().unwrap().push(Box::new(t)); } }
}
fn fundamental() {
    {
        let l = String::from("whats up global community, that is lengthy sufficient");
        let mut q = Q(None);
        q.0 = Some(&l);
    }
    let _z = String::from("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    let ok = KEPT.lock().unwrap();
    println!("{}", ok[0].downcast_ref::<&'static String>().unwrap());
}

I anticipated to see this occur: program isn’t accepted

Instead, this occurred: program compiles and prints XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. With asan, this system will crash with a AddressSanitizer: stack-use-after-scope

Meta

Issue on present nightly, and stables no less than all the way down to 1.85.0

Godbolt with asan: https://rust.godbolt.org/z/83MvfbKde
Godbolt with out asan: https://rust.godbolt.org/z/GsGdqqMWe



Source link