Box<T>型

doc.rust-lang.org

Rustの全ての値は、デフォルトはstack領域で確保される。 値は、Box<T>を生成することによって、boxed(ヒープ上での確保)することが出来る。

box値は、T型の値をヒープ上に確保するためのスマートポインタである。

box値がスコープから消えた場合は、デストラクタが呼ばれ、内部のオブジェクトは破壊され、メモリが開放される。

ボックスされた値は、*演算子を使用することで、デリファレンスされることが出来る。

Note: デリファレンス

  • スマートポインタ 内部の値を返す
  • 参照型 参照先の取得 (参照を外す)
use std::mem;

#[derive(Debug)]
struct Point {
    x: f64,    // 8 bytes
    y: f64,    // 8 bytes
}
#[derive(Debug)]
struct Rectangle {
    top_left: Point,     // 16 bytes
    bottom_right: Point, // 16 bytes
}

fn main() {
    let rectangle = Rectangle {
        top_left: Point { x: 0.0, y: 0.0 },
        bottom_right: Point { x: 2.0, y: -4.0 },
    };
    println!("Rectangle occupies {} bytes on the stack", mem::size_of_val(&rectangle)); // 32 bytes

    let boxed_rectangle = Box::new(rectangle);
    println!("Boxed rectangle occupies {} bytes on the stack", mem::size_of_val(&boxed_rectangle)); // 8 bytes

    // Copyトレイトでないので、デリファレンスによって値の所有権が移動する
    let unboxed_rectangle = *boxed_rectangle;
    println!("Unboxed point occpies {} bytes on the stack", mem::size_of_val(&unboxed_rectangle)); // 32 bytes
}

関連

users.rust-lang.org

https://yossan.hatenablog.com/entry/2020/09/20/224329

https://yossan.hatenablog.com/entry/2021/02/02/213844