|
2 | 2 |
|
3 | 3 | Variables in Rust do more than just hold data in the stack: they also *own*
|
4 | 4 | resources, e.g. `Box<T>` owns memory in the heap. Rust enforces [RAII][raii]
|
5 |
| -(Resource Acquisition Is Initialization), so whenever an object goes out of |
6 |
| -scope, its destructor is called and its owned resources are freed. |
| 5 | +(Resource Acquisition Is Initialization), so whenever an object goes out of |
| 6 | +scope, its destructor is called and its owned resources are freed. |
7 | 7 |
|
8 |
| -This behavior shields against *resource leak* bugs, so you'll never have to |
| 8 | +This behavior shields against *resource leak* bugs, so you'll never have to |
9 | 9 | manually free memory or worry about memory leaks again! Here's a quick showcase:
|
10 | 10 |
|
11 | 11 | ```rust,editable
|
@@ -61,10 +61,36 @@ $ rustc raii.rs && valgrind ./raii
|
61 | 61 |
|
62 | 62 | No leaks here!
|
63 | 63 |
|
| 64 | +## Destructor |
| 65 | +
|
| 66 | +The notion of a destructor in Rust is provided through the [`Drop`] trait. The |
| 67 | +destructor is called when the resource goes out of scope. This trait is not |
| 68 | +required to be implemented for every type, only implement it for your type if |
| 69 | +you require its own destructor logic. |
| 70 | +
|
| 71 | +Run the below example to see how the [`Drop`] trait works. When the variable in |
| 72 | +the `main` function goes out of scope the custom destructor wil be invoked. |
| 73 | +
|
| 74 | +```rust,editable |
| 75 | +struct ToDrop; |
| 76 | +
|
| 77 | +impl Drop for ToDrop { |
| 78 | + fn drop(&mut self) { |
| 79 | + println!("ToDrop is being dropped"); |
| 80 | + } |
| 81 | +} |
| 82 | +
|
| 83 | +fn main() { |
| 84 | + let x = ToDrop; |
| 85 | + println!("Made a ToDrop!"); |
| 86 | +} |
| 87 | +``` |
| 88 | +
|
64 | 89 | ### See also:
|
65 | 90 |
|
66 | 91 | [Box][box]
|
67 | 92 |
|
68 | 93 | [raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
|
69 | 94 | [box]: /std/box.html
|
70 |
| -[valgrind]: http://valgrind.org/info/ |
| 95 | +[valgrind]: http://valgrind.org/info/ |
| 96 | +[`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html |
0 commit comments