什么是创建盒子< [t]>哪个是空的?
box ::来自()或 slice :: in()。
box ::来自()
slice :: in()
这样的盒子应该有效地成为一个悬挂的指针,其长度为零,什么都不应分配,对
编号 [T] 是一个切片,是DST。在这种情况下, box 将是一个胖指针,盒子本身持有元数据(切片的大小):
[T]
box
let ar = [0;5]; let boxed: Box<[_]> = ar[..].into(); println!("{}", std::mem::size_of_val(&boxed));
即使下层切片为空,也将打印16(例如 ar [..0] )。
ar [..0]
但是,如果值是ZST(例如 box&lt; [_; 0]&gt; ),那么确实确实有一个特殊情况:
box&lt; [_; 0]&gt;
What is the most canonical way to create Box<[T]> which is empty?
Box::from() or slice::into().
Box::from()
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):
Box
will print 16, even if the underlying slice is empty (e.g. ar[..0]).
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
Box<[_;0]>
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(1)
box ::来自()
或slice :: in()
。编号
[T]
是一个切片,是DST。在这种情况下,box
将是一个胖指针,盒子本身持有元数据(切片的大小):即使下层切片为空,也将打印16(例如
ar [..0]
)。但是,如果值是ZST(例如
box&lt; [_; 0]&gt;
),那么确实确实有一个特殊情况:Box::from()
orslice::into()
.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):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