Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A couple of fixes for the Box, stack and heap chapter. #1206

Merged
merged 2 commits into from
Jun 24, 2019
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
20 changes: 10 additions & 10 deletions src/std/box.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Box, stack and heap

All values in Rust are stack allocated by default. Values can be *boxed*
(allocated in the heap) by creating a `Box<T>`. A box is a smart pointer to a
(allocated on the heap) by creating a `Box<T>`. A box is a smart pointer to a
heap allocated value of type `T`. When a box goes out of scope, its destructor
is called, the inner object is destroyed, and the memory in the heap is freed.
is called, the inner object is destroyed, and the memory on the heap is freed.

Boxed values can be dereferenced using the `*` operator; this removes one layer
of indirection.
Expand All @@ -29,7 +29,7 @@ fn origin() -> Point {
}

fn boxed_origin() -> Box<Point> {
// Allocate this point in the heap, and return a pointer to it
// Allocate this point on the heap, and return a pointer to it
Box::new(Point { x: 0.0, y: 0.0 })
}

Expand All @@ -54,22 +54,22 @@ fn main() {
// Double indirection
let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());

println!("Point occupies {} bytes in the stack",
println!("Point occupies {} bytes on the stack",
mem::size_of_val(&point));
println!("Rectangle occupies {} bytes in the stack",
println!("Rectangle occupies {} bytes on the stack",
mem::size_of_val(&rectangle));

// box size = pointer size
println!("Boxed point occupies {} bytes in the stack",
// box size == pointer size
println!("Boxed point occupies {} bytes on the stack",
mem::size_of_val(&boxed_point));
println!("Boxed rectangle occupies {} bytes in the stack",
println!("Boxed rectangle occupies {} bytes on the stack",
mem::size_of_val(&boxed_rectangle));
println!("Boxed box occupies {} bytes in the stack",
println!("Boxed box occupies {} bytes on the stack",
mem::size_of_val(&box_in_a_box));

// Copy the data contained in `boxed_point` into `unboxed_point`
let unboxed_point: Point = *boxed_point;
println!("Unboxed point occupies {} bytes in the stack",
println!("Unboxed point occupies {} bytes on the stack",
mem::size_of_val(&unboxed_point));
}
```