- Box, 以及栈和堆
Box, 以及栈和堆
在 Rust 中,所有值默认都由栈分配。值也可以通过创建 Box<T> 来装箱(boxed,分配在堆上)。装箱类型是一个智能指针,指向堆分配的 T 类型的值。当一个装箱类型离开作用域时,它的析构器会被调用,内部的对象会被销毁,分配在堆上内存会被释放。
装箱的值可以使用 * 运算符进行解引用;这会移除掉一个间接层(this removes one layer of indirection. )。
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 }};// 堆分配的 rectangle(矩形)let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {p1: origin(),p2: origin()});// 函数的输出可以装箱(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 in the stack",mem::size_of_val(&point));println!("Rectangle occupies {} bytes in the stack",mem::size_of_val(&rectangle));// box 的大小 = 指针 大小(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));}
