1
1
# Box, stack and heap
2
2
3
3
All values in Rust are stack allocated by default. Values can be * boxed*
4
- (allocated in the heap) by creating a ` Box<T> ` . A box is a smart pointer to a
4
+ (allocated on the heap) by creating a ` Box<T> ` . A box is a smart pointer to a
5
5
heap allocated value of type ` T ` . When a box goes out of scope, its destructor
6
- is called, the inner object is destroyed, and the memory in the heap is freed.
6
+ is called, the inner object is destroyed, and the memory on the heap is freed.
7
7
8
8
Boxed values can be dereferenced using the ` * ` operator; this removes one layer
9
9
of indirection.
@@ -29,7 +29,7 @@ fn origin() -> Point {
29
29
}
30
30
31
31
fn boxed_origin() -> Box<Point> {
32
- // Allocate this point in the heap, and return a pointer to it
32
+ // Allocate this point on the heap, and return a pointer to it
33
33
Box::new(Point { x: 0.0, y: 0.0 })
34
34
}
35
35
@@ -54,22 +54,22 @@ fn main() {
54
54
// Double indirection
55
55
let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());
56
56
57
- println!("Point occupies {} bytes in the stack",
57
+ println!("Point occupies {} bytes on the stack",
58
58
mem::size_of_val(&point));
59
- println!("Rectangle occupies {} bytes in the stack",
59
+ println!("Rectangle occupies {} bytes on the stack",
60
60
mem::size_of_val(&rectangle));
61
61
62
- // box size = pointer size
63
- println!("Boxed point occupies {} bytes in the stack",
62
+ // box size == pointer size
63
+ println!("Boxed point occupies {} bytes on the stack",
64
64
mem::size_of_val(&boxed_point));
65
- println!("Boxed rectangle occupies {} bytes in the stack",
65
+ println!("Boxed rectangle occupies {} bytes on the stack",
66
66
mem::size_of_val(&boxed_rectangle));
67
- println!("Boxed box occupies {} bytes in the stack",
67
+ println!("Boxed box occupies {} bytes on the stack",
68
68
mem::size_of_val(&box_in_a_box));
69
69
70
70
// Copy the data contained in `boxed_point` into `unboxed_point`
71
71
let unboxed_point: Point = *boxed_point;
72
- println!("Unboxed point occupies {} bytes in the stack",
72
+ println!("Unboxed point occupies {} bytes on the stack",
73
73
mem::size_of_val(&unboxed_point));
74
74
}
75
75
```
0 commit comments