drop trait是指当一个值离开作用域的时候会发生的事情,比如Box<T>在离开作用域的时候会清理堆上的数据
有些编程语言没有GC机制,程序要在使用完智能指针之后需要手动清理内存,Rust可以让我们插入一小断代码,当变量离开作用域的时候使用
这段代码就是实现Drop trait
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
fn main() {
let c = CustomSmartPointer {
data: String::from("my stuff"),
};
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
println!("CustomSmartPointers created.");
}
不能够显示的调用drop()方法,就像下面这样就会报错,也不能阻止drop方法
fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created.");
c.drop();
println!("CustomSmartPointer dropped before the end of main.");
}
如果我们想强制回收资源,可以使用std::mem::drop方法
fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created.");
drop(c);
println!("CustomSmartPointer dropped before the end of main.");
}
|