17.1 Box, stack and heap
Rust에서 사용되는 값들은 기본적으로 스택에 할당된다. 값은 boxed(힙에 할당)를 통해 Box<T>를 만들 수 있다. box는 타입 T의 힙에 할당된 값의 스마트 포인터이다. box가 범위에서 벗어나면, 그의 소멸자가 호출되고, 내부 개체는 제거되며, 힙의 메모리는 해제된다.
Box된 값은 * 연산자를 사용하여 역참조 될 수 있다; 이는 간접 참조 계층을 제거한다.
use std::mem;
#[derive(Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
fn boxed_origin() -> Box<Point> {
// 이 Point를 힙에 할당하고, 그 포인터를 반환.
Box::new(Point { x: 0.0, y: 0.0 })
}
fn main() {
// 스택에 변수들을 할당
let point: Point = origin();
let rectangle: Rectangle = Rectangle {
p1: origin(),
p2: Point { x: 3.0, y: 4.0 }
};
// 힙에 할당된 직사각형.
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
p1: origin(),
p2: origin()
});
// 함수 출력물도 box될 수 있다.
let boxed_point: Box<Point> = Box::new(origin());
// 이중 간접 참조.
let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());
println!("Point occupies {} bytes in the stack",
mem::size_of_val(&point));
println!("Rectangle occupies {} bytes in the stack",
mem::size_of_val(&rectangle));
// box size = pointer size
println!("Boxed point occupies {} bytes in the stack",
mem::size_of_val(&boxed_point));
println!("Boxed rectangle occupies {} bytes in the stack",
mem::size_of_val(&boxed_rectangle));
println!("Boxed box occupies {} bytes in the stack",
mem::size_of_val(&box_in_a_box));
// `boxed_point`의 데이터를 복사해 `unboxed_point`에 넣기.
let unboxed_point: Point = *boxed_point;
println!("Unboxed point occupies {} bytes in the stack",
mem::size_of_val(&unboxed_point));
}