Box, 스택 및 힙

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩에서는 Rust 의 boxing, 스택 할당, 힙 할당의 개념을 탐구합니다. Rust 의 모든 값은 기본적으로 스택에 할당되지만, Box<T> 타입을 사용하여 boxing(힙에 할당) 할 수 있습니다. Box 는 힙에 할당된 값을 가리키는 스마트 포인터이며, scope 밖으로 벗어날 때 소멸자가 호출되어 힙의 메모리가 해제됩니다. Boxing 을 통해 이중 간접 참조 (double indirection) 를 생성할 수 있으며, * 연산자를 사용하여 역참조 (dereference) 할 수 있습니다. 이 랩에서는 boxing 이 어떻게 작동하고 스택의 메모리 할당에 어떤 영향을 미치는지에 대한 코드 예제와 설명을 제공합니다.

참고: 랩에서 파일 이름을 지정하지 않은 경우, 원하는 파일 이름을 사용할 수 있습니다. 예를 들어, main.rs를 사용하고 rustc main.rs && ./main으로 컴파일하고 실행할 수 있습니다.

Box, 스택 및 힙

Rust 의 모든 값은 기본적으로 스택에 할당됩니다. Box<T>를 생성하여 값을 boxing (힙에 할당) 할 수 있습니다. Box 는 T 타입의 힙에 할당된 값을 가리키는 스마트 포인터입니다. Box 가 scope 밖으로 벗어날 때 소멸자가 호출되고, 내부 객체가 파괴되며, 힙의 메모리가 해제됩니다.

Box 된 값은 * 연산자를 사용하여 역참조 (dereference) 할 수 있습니다. 이는 간접 참조의 한 단계를 제거합니다.

use std::mem;

#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
struct Point {
    x: f64,
    y: f64,
}

// A Rectangle can be specified by where its top left and bottom right
// corners are in space
#[allow(dead_code)]
struct Rectangle {
    top_left: Point,
    bottom_right: Point,
}

fn origin() -> Point {
    Point { x: 0.0, y: 0.0 }
}

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

fn main() {
    // (all the type annotations are superfluous)
    // Stack allocated variables
    let point: Point = origin();
    let rectangle: Rectangle = Rectangle {
        top_left: origin(),
        bottom_right: Point { x: 3.0, y: -4.0 }
    };

    // Heap allocated rectangle
    let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
        top_left: origin(),
        bottom_right: Point { x: 3.0, y: -4.0 },
    });

    // The output of functions can be boxed
    let boxed_point: Box<Point> = Box::new(origin());

    // Double indirection
    let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());

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

    // box size == pointer size
    println!("Boxed point occupies {} bytes on the stack",
             mem::size_of_val(&boxed_point));
    println!("Boxed rectangle occupies {} bytes on the stack",
             mem::size_of_val(&boxed_rectangle));
    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 on the stack",
             mem::size_of_val(&unboxed_point));
}

요약

축하합니다! Box, Stack 및 Heap 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 실력을 향상시킬 수 있습니다.