英文:
If a struct has a Vector field, does it get allocated on the heap?
问题
Train
结构体将被分配在堆栈上,但它的字段 passenger_ids
会指向堆上的数据,因为它是 Vector 类型,Vector 内的元素通常会分配在堆上。
英文:
Suppose I have a struct Train
which contains a field called passenger_ids
which itself represents a Vector of passenger identifiers.
struct Train {
passenger_ids: Vector<u32>
}
Would Train
be allocated on the heap since it holds a field of type Vector (which is allocated on the heap)? Or would it instead be allocated on the stack and the field point towards the heap?
答案1
得分: 4
No, a train would not be allocated on the heap, and no a vector is not allocated on the heap.
A Vec
is a normal structure which contains a pointer to a heap allocation. The Train
, and the Vec
it contains, will be allocated as a single unit wherever they are put (whether that's on the stack, or on the heap if Box
-ed, or somewhere else).
The Vec
will then, if and when items get added to it, create a heap allocation and put the items there.
英文:
> Would Train be allocated on the heap since it holds a field of type Vector (which is allocated on the heap)? Or would it instead be allocated on the stack and the field point towards the heap?
No, a train would not be allocated on the heap, and no a vector is not allocated on the heap.
A Vec
is a normal structure which contains a pointer to a heap allocation. The Train
, and the Vec
it contains, will be allocated as a single unit wherever they are put (whether that's on the stack, or on the heap if Box
-ed, or somewhere else).
The Vec
will then, if and when items get added to it, create a heap allocation and put the items there.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论