Skip to content

Commit 1788c74

Browse files
authored
Merge pull request #943 from maccoda/raii_467
Adding destructor.
2 parents ef42a1c + 3431de3 commit 1788c74

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

src/scope/raii.md

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
Variables in Rust do more than just hold data in the stack: they also *own*
44
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.
77

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
99
manually free memory or worry about memory leaks again! Here's a quick showcase:
1010

1111
```rust,editable
@@ -61,10 +61,36 @@ $ rustc raii.rs && valgrind ./raii
6161
6262
No leaks here!
6363
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+
6489
### See also:
6590
6691
[Box][box]
6792
6893
[raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
6994
[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

Comments
 (0)