如果一个结构体有一个Vector字段,它会被分配到堆上吗?

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月7日 01:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定