src/memory-management/drop.md
Drop TraitValues which implement Drop can specify code to run when they go out of
scope:
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
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 innermost block");
}
println!("Exiting next block");
}
drop(a);
println!("Exiting main");
}
std::mem::drop is not the same as std::ops::Drop::drop.std::ops::Drop then its
Drop::drop implementation will be called.Drop.std::mem::drop is 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.
drop: releasing locks,
closing files, etc.Discussion points:
Drop::drop take self?
std::mem::drop would be called at the end of the
block, resulting in another call to Drop::drop, and a stack overflow!drop(a) with a.drop().