Why Drop trait not called when use global static

help me to understand this code.
and why drop function not called automaticaly

use std::ops::Drop;


static mut BASE_CORE: Option<Core> = None;

struct Core {
    ver: String,
    name: String
}

impl Core {
    pub fn new() -> Core {
        Core {
            ver: String::from("some ver 0.0.0"),
            name: String::from("Im Core")
        }
    }
}

impl Drop for Core {
    fn drop(&mut self) {
        println!("OnDrop: {} {}", self.ver, self.name);
    }
}

struct Base {
    astr: String
}

impl Base {

    pub fn new () -> Base {
        unsafe {
            BASE_CORE = Some(Core::new());
        }

        Base {
            astr: String::from("from base")
        }
    }

    pub fn print_msg(&self) {
        println!("{}", self.astr)
    }

}


fn main() {
    // var1 when exit drop function not called automaticaly
    let var1 = Base::new();
    var1.print_msg();

    let _var2 = Core::new();

}

Because you can reference statics in Drop implementations, so there's no way to know what order in which to run them.

(And the OS will cleanup memory and such from them anyway, so in most cases it's actually better not to run them.)

4 Likes

static variables, by definition, must remain valid until the very last moment of program execution. They’re never dropped because there would be some time after drop is run and before the program exits where they’re not valid.

This comes into play, for example, if several static variables implement Drop. One of them must be dropped first. The others’ drop functions must run with the program in an illegal state: A value that’s supposed to always be available is now inaccessible.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.