• Box, 以及栈和堆

    Box, 以及栈和堆

    在 Rust 中,所有值默认都由栈分配。值也可以通过创建 Box<T>装箱(boxed,分配在堆上)。装箱类型是一个智能指针,指向堆分配的 T 类型的值。当一个装箱类型离开作用域时,它的析构器会被调用,内部的对象会被销毁,分配在堆上内存会被释放。

    装箱的值可以使用 * 运算符进行解引用;这会移除掉一个间接层(this removes one layer of indirection. )。

    1. use std::mem;
    2. #[derive(Clone, Copy)]
    3. struct Point {
    4. x: f64,
    5. y: f64,
    6. }
    7. #[allow(dead_code)]
    8. struct Rectangle {
    9. p1: Point,
    10. p2: Point,
    11. }
    12. fn origin() -> Point {
    13. Point { x: 0.0, y: 0.0 }
    14. }
    15. fn boxed_origin() -> Box<Point> {
    16. // 在堆上分配这个点(point),并返回一个指向它的指针
    17. Box::new(Point { x: 0.0, y: 0.0 })
    18. }
    19. fn main() {
    20. // (所有的类型标注都是可要可不要的)
    21. // 栈分配的变量
    22. let point: Point = origin();
    23. let rectangle: Rectangle = Rectangle {
    24. p1: origin(),
    25. p2: Point { x: 3.0, y: 4.0 }
    26. };
    27. // 堆分配的 rectangle(矩形)
    28. let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
    29. p1: origin(),
    30. p2: origin()
    31. });
    32. // 函数的输出可以装箱(boxed)
    33. let boxed_point: Box<Point> = Box::new(origin());
    34. // 双重间接装箱(Double indirection)
    35. let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());
    36. println!("Point occupies {} bytes in the stack",
    37. mem::size_of_val(&point));
    38. println!("Rectangle occupies {} bytes in the stack",
    39. mem::size_of_val(&rectangle));
    40. // box 的大小 = 指针 大小(box size = pointer size)
    41. println!("Boxed point occupies {} bytes in the stack",
    42. mem::size_of_val(&boxed_point));
    43. println!("Boxed rectangle occupies {} bytes in the stack",
    44. mem::size_of_val(&boxed_rectangle));
    45. println!("Boxed box occupies {} bytes in the stack",
    46. mem::size_of_val(&box_in_a_box));
    47. // 将包含在 `boxed_point` 的数据复制到 `unboxed_point`
    48. let unboxed_point: Point = *boxed_point;
    49. println!("Unboxed point occupies {} bytes in the stack",
    50. mem::size_of_val(&unboxed_point));
    51. }