What is the difference between Vec<i32> and Vec<Box<i32>>?

这一生的挚爱 提交于 2021-02-07 11:55:38

问题


let vec1 = vec![1, 2, 3, 4];
let vec2 = vec![Box::new(1), Box::new(2), Box::new(3), Box::new(4)];

What is the difference between them? I have already allocated vec1 on the heap. So aren't all the elements of vec1 also on the heap? Why would I need to separately allocate them on the heap like in vec2?


回答1:


I'll draw a diagram. The first value is a pointer to a contiguous array of numbers on the heap.

(stack)    (heap)
┌──────┐   ┌───┐
│ vec1 │──→│ 1 │
└──────┘   ├───┤
           │ 2 │
           ├───┤
           │ 3 │
           ├───┤
           │ 4 │
           └───┘

The second version adds extra indirection. The elements are still on the heap, but now they're somewhere else on the heap.

(stack)    (heap)   ┌───┐
┌──────┐   ┌───┐ ┌─→│ 1 │
│ vec2 │──→│   │─┘  └───┘
└──────┘   ├───┤    ┌───┐
           │   │───→│ 2 │
           ├───┤    └───┘
           │   │─┐  ┌───┐
           ├───┤ └─→│ 3 │
           │   │─┐  └───┘
           └───┘ │  ┌───┐
                 └─→│ 4 │
                    └───┘

Due to the way ownership works in Rust, you are not going to run into any semantic differences. The extra indirection gives you worse memory usage and cache locality.




回答2:


vec![1, 2, 3, 4] is a vector of i32s.

vec![Box::new(1), Box::new(2), Box::new(3), Box::new(4)] is a vector of owned pointers to i32s. Rust's owned pointer is similar to C++'s unique_ptr.



来源:https://stackoverflow.com/questions/21066133/what-is-the-difference-between-veci32-and-vecboxi32

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!