文档说明如果类型有析构函数,将不会调用该函数:https://docs.rs/lazy_static/1.4.0/lazy_static/#semantics。那么我该如何释放内存呢?
lazy_static
变量改为 Option
,并在不再需要时调用 take()
方法来释放内存。例如:lazy_static! {
static ref LARGE: Mutex<Option<String>> =
Mutex::new(Some(iter::repeat('x').take(1_000_000).collect()));
}
fn main() {
println!("using the string: {}", LARGE.lock().as_ref().unwrap().len());
LARGE.lock().take();
println!("string freed")
assert!(LARGE.lock().is_none());
}
就像其他人指出的那样,在大多数情况下没有必要这样做,因为大多数全局变量的目的是持续到程序结束,即使析构函数从未运行,内存也将被操作系统回收。
如果全局变量与您在程序中某个点之后不再需要的资源相关联,则上述方法可能会有用。
static
变量的行为,不仅仅是lazy_static
。请参阅 Rust 参考中的[静态变量] (https://doc.rust-lang.org/reference/items/static-items.html):“在程序结束时,静态项不会调用 drop”。 - kmdreko