El Trait Drop
Los valores que implementan Drop pueden especificar el código que se ejecutará cuando salgan del ámbito:
struct Droppable { name: &'static str, } impl Drop for Droppable { fn drop(&mut self) { println!("Dropping {}", self.name); } } fn main() { let a = Droppable { name: "a" }; { let b = Droppable { name: "b" }; { let c = Droppable { name: "c" }; let d = Droppable { name: "d" }; println!("Exiting block B"); } println!("Exiting block A"); } drop(a); println!("Exiting main"); }
This slide should take about 10 minutes.
- Note that
std::mem::dropis not the same asstd::ops::Drop::drop. - Values are automatically dropped when they go out of scope.
- When a value is dropped, if it implements
std::ops::Dropthen itsDrop::dropimplementation will be called. - All its fields will then be dropped too, whether or not it implements
Drop. std::mem::dropis just an empty function that takes any value. The significance is that it takes ownership of the value, so at the end of its scope it gets dropped. This makes it a convenient way to explicitly drop values earlier than they would otherwise go out of scope.- This can be useful for objects that do some work on
drop: releasing locks, closing files, etc.
- This can be useful for objects that do some work on
Cuestiones de debate:
- ¿Por qué
Drop::dropno aceptaself?- Respuesta corta: si lo hiciera, se llamaría a
std::mem::dropal final del bloque, lo que daría como resultado otra llamada aDrop::dropy un desbordamiento de la stack.
- Respuesta corta: si lo hiciera, se llamaría a
- Prueba a sustituir
drop(a)pora.drop().