如果我制作一个结构并将其放在向量中,它是驻留在堆还是堆栈上? [英] If I make a struct and put it in a vector, does it reside on the heap or the stack?

查看:65
本文介绍了如果我制作一个结构并将其放在向量中,它是驻留在堆还是堆栈上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些生成几何元素向量的代码:

I'm writing some code that generates a vector of geometric elements:

struct Geom_Entity {
    // a bunch of geometric information,
    // like tangent planes, force vectors, etc
}

代码正在从文本文件中解析许多这样的实体(例如),因此我们目前有一个功能:

The code is parsing many of these entities from a text file (for e.g.) so we have a function currently:

parse_Geom(x: String) -> Vec<Geom_Entity> { 
    // a bunch of code
}

这些几何实体是具有17个f64和其他一些字段的大型结构.该文件可能包含其中的1000多个,但数量不足以至于它们无法全部放入内存中(至少现在是这样).

These geometric entities are large structs with 17 f64s and a few other fields. The file may contain well over 1000 of these, but not so many that they can't all fit into memory (at least for now).

我也应该做

Box::new(Geom_Entity { ...

然后将框放入向量中?

推荐答案

The documentation for Vec says (emphasis mine):

如果Vec已分配内存,则它指向的内存在堆上

If a Vec has allocated memory, then the memory it points to is on the heap

是的,向量的成员归向量所有并存储在堆中.

So yes, the members of the vector are owned by the vector and are stored on the heap.

general 中,在将元素放入Vec之前将其装箱是浪费的-额外的内存分配和间接寻址.有时候,您需要额外的分配或间接分配,因此永远不要说永不.

In general, boxing an element before putting it in the Vec is wasteful - there's extra memory allocation and indirection. There are times when you need that extra allocation or indirection, so it's never say never.

另请参阅:

这篇关于如果我制作一个结构并将其放在向量中,它是驻留在堆还是堆栈上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆