根据我的理解,编译器会自动生成代码,以便在范围结束时调用析构函数来删除不再需要的对象。
在某些情况下,一旦不再需要删除对象,而不是等待它超出范围,这是有益的。是否可以在Rust中显式调用对象的析构函数?
答案 0 :(得分:16)
在Rust中是否可以在范围结束之前删除对象?
是
是否可以在Rust中显式调用对象的析构函数?
没有
为了澄清,您可以使用std::mem::drop
转移变量的所有权,这会导致变量超出范围:
struct Noisy;
impl Drop for Noisy {
fn drop(&mut self) {
println!("Dropping Noisy!");
}
}
fn main() {
let a = Noisy;
let b = Noisy;
println!("1");
drop(b);
println!("2");
}
1
Dropping Noisy!
2
Dropping Noisy!
但是,您被禁止自己调用析构函数(Drop
特征的实现)。这样做会导致双重自由情况,因为编译器仍会将自动调用插入Drop
特征。
有趣的旁注 - drop
的实施非常优雅:
pub fn drop<T>(_x: T) { }
答案 1 :(得分:13)
官方答复是致电mem::drop
:
fn do_the_thing() {
let s = "Hello, World".to_string();
println!("{}", s);
drop(s);
println!("{}", 3);
}
但请注意,mem::drop
并不特别。这是the definition in full:
pub fn drop<T>(_x: T) { }
这就是全部。
任何参数所有权的函数都会导致在所述函数结束时删除此参数。从呼叫者的角度来看,这是一个早期下降:)