何时使用Box< Vec>。或Vec< Box< ..>吗? [英] When to use Box<Vec<..>> or Vec<Box<..>>?

查看:92
本文介绍了何时使用Box< Vec>。或Vec< Box< ..>吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候设计一个嵌套 Box Vec 的数据结构(反之亦然)

When would it make sense to design a data structure that is nesting a Box and a Vec (or vice versa)?

在大多数情况下,您想在堆上存储多个固定大小的东西,即 Box 是多余的,因为它的唯一(?)角色是堆分配〜单个值,而普通的 Vec 已经在堆中分配其存储空间。

It seems like in most situations where you want to store multiple fixed-size things on the heap, the Box is redundant, since it's only (?) role is to heap-allocate a ~single value, and a normal Vec is already heap allocating it's storage.

上下文:我仍在围绕各种Rust类型的角色来构建数据结构。

Context: I am still wrapping my head around the roles of the various Rust types for building up data structures.

推荐答案

实际上只需要几次使用 Box

There are really only a few times you need to use Box:


  • 递归数据结构:与最外面的元素无关,因此不需要 Vec< Box< T>>

自有特征对象,该对象必须是 Box< Trait> ,因为对象的大小是动态的;

Owned trait object, which must be Box<Trait> because the size of the object is dynamic;

对特定内存敏感的内容Ory地址,以使所包含的对象保持相同的内存位置(实际上从来没有,而且在任何稳定的公共API中绝对不是这种情况;我只知道与 std :: sync :: mpsc :: Select 有关的一些句柄。这种不安全和必要的护理是为什么 select的一部分! 存在。这种东西( Handle.add )是不安全的东西。

Things that are sensitive to particular memory addresses, in order that the contained object will keep the same memory location (practically never the case and definitely not the case in any stable public API; some of the handle stuff to do with std::sync::mpsc::Select is the only case that I am aware of; this unsafety and care required is a part of why select! exists. This sort of a thing (Handle.add) is unsafe stuff.

如果以上情况均不适用,则您不应使用 Box 。而 Box< Vec< T>> 就是这种情况之一;

If none of these situations apply, you should not use Box. And Box<Vec<T>> is one such case; the boxing is completely superfluous, adding an additional level of indirection to no benefit whatsoever.

所以简单的版本是:


  • Box< Vec< T>> :从不。

  • Vec< Box< T>> :仅当 T 是特征时,即您正在使用特征对象。

  • Box<Vec<T>>: never.
  • Vec<Box<T>>: only if T is a trait, i.e. you’re working with trait objects.

这篇关于何时使用Box&lt; Vec&gt;。或Vec&lt; Box&lt; ..&gt;吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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