创建空盒装切片

发布于 2025-01-21 04:13:47 字数 1398 浏览 3 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉酒的小男人 2025-01-28 04:13:47

什么是创建盒子< [t]>哪个是空的?

box ::来自() slice :: in()

这样的盒子应该有效地成为一个悬挂的指针,其长度为零,什么都不应分配,对

编号 [T] 是一个切片,是DST。在这种情况下, box 将是一个胖指针,盒子本身持有元数据(切片的大小):

let ar = [0;5];
let boxed: Box<[_]> = ar[..].into();
println!("{}", std::mem::size_of_val(&boxed));

即使下层切片为空,也将打印16(例如 ar [..0] )。

但是,如果值是ZST(例如 box&lt; [_; 0]&gt; ),那么确实确实有一个特殊情况:

What is the most canonical way to create Box<[T]> which is empty?

Box::from() or slice::into().

Such box should effectively just become a dangling pointer with zero length and nothing should be allocated, right?

No. [T] is a slice, which is a DST. In such a case, Box would be a fat pointer, with box itself holding the metadata (the size of the slice):

let ar = [0;5];
let boxed: Box<[_]> = ar[..].into();
println!("{}", std::mem::size_of_val(&boxed));

will print 16, even if the underlying slice is empty (e.g. ar[..0]).

If the value is a ZST however (e.g. Box<[_;0]>) then there is indeed a special case to not allocate: https://github.com/rust-lang/rust/blob/9c09c1f7cfcf9de0522bcd1cfda32b552195c464/library/alloc/src/alloc.rs#L163

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文