Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/scope/raii.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

Variables in Rust do more than just hold data in the stack: they also *own*
resources, e.g. `Box<T>` owns memory in the heap. Rust enforces [RAII][raii]
(Resource Acquisition Is Initialization), so whenever an object goes out of
scope, its destructor is called and its owned resources are freed.
(Resource Acquisition Is Initialization), so whenever an object goes out of
scope, its destructor is called and its owned resources are freed.

This behavior shields against *resource leak* bugs, so you'll never have to
This behavior shields against *resource leak* bugs, so you'll never have to
manually free memory or worry about memory leaks again! Here's a quick showcase:

```rust,editable
Expand Down Expand Up @@ -61,10 +61,36 @@ $ rustc raii.rs && valgrind ./raii

No leaks here!

## Destructor

The notion of a destructor in Rust is provided through the [`Drop`] trait. The
destructor is called when the resource goes out of scope. This trait is not
required to be implemented for every type, only implement it for your type if
you require its own destructor logic.

Run the below example to see how the [`Drop`] trait works. When the variable in
the `main` function goes out of scope the custom destructor wil be invoked.

```rust,editable
struct ToDrop;

impl Drop for ToDrop {
fn drop(&mut self) {
println!("ToDrop is being dropped");
}
}

fn main() {
let x = ToDrop;
println!("Made a ToDrop!");
}
```

### See also:

[Box][box]

[raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
[box]: /std/box.html
[valgrind]: http://valgrind.org/info/
[valgrind]: http://valgrind.org/info/
[`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html