]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Ownership and moves |
2 | ||
3 | Because variables are in charge of freeing their own resources, | |
ed00b5ec | 4 | **resources can only have one owner**. This prevents resources |
2c00a5a8 XL |
5 | from being freed more than once. Note that not all variables own |
6 | resources (e.g. [references]). | |
7 | ||
8 | When doing assignments (`let x = y`) or passing function arguments by value | |
9 | (`foo(x)`), the *ownership* of the resources is transferred. In Rust-speak, | |
10 | this is known as a *move*. | |
11 | ||
12 | After moving resources, the previous owner can no longer be used. This avoids | |
13 | creating dangling pointers. | |
14 | ||
15 | ```rust,editable | |
16 | // This function takes ownership of the heap allocated memory | |
17 | fn destroy_box(c: Box<i32>) { | |
18 | println!("Destroying a box that contains {}", c); | |
19 | ||
20 | // `c` is destroyed and the memory freed | |
21 | } | |
22 | ||
23 | fn main() { | |
24 | // _Stack_ allocated integer | |
25 | let x = 5u32; | |
26 | ||
27 | // *Copy* `x` into `y` - no resources are moved | |
28 | let y = x; | |
29 | ||
30 | // Both values can be independently used | |
31 | println!("x is {}, and y is {}", x, y); | |
32 | ||
33 | // `a` is a pointer to a _heap_ allocated integer | |
34 | let a = Box::new(5i32); | |
35 | ||
36 | println!("a contains: {}", a); | |
37 | ||
38 | // *Move* `a` into `b` | |
39 | let b = a; | |
40 | // The pointer address of `a` is copied (not the data) into `b`. | |
41 | // Both are now pointers to the same heap allocated data, but | |
42 | // `b` now owns it. | |
43 | ||
44 | // Error! `a` can no longer access the data, because it no longer owns the | |
45 | // heap memory | |
46 | //println!("a contains: {}", a); | |
47 | // TODO ^ Try uncommenting this line | |
48 | ||
49 | // This function takes ownership of the heap allocated memory from `b` | |
50 | destroy_box(b); | |
51 | ||
52 | // Since the heap memory has been freed at this point, this action would | |
53 | // result in dereferencing freed memory, but it's forbidden by the compiler | |
54 | // Error! Same reason as the previous Error | |
55 | //println!("b contains: {}", b); | |
56 | // TODO ^ Try uncommenting this line | |
57 | } | |
58 | ``` | |
59 | ||
dc9dc135 | 60 | [references]: ../flow_control/match/destructuring/destructure_pointers.md |