您现在的位置是:挑肥拣瘦网 > 热点
揭开智能指针 Box 的神秘面纱
挑肥拣瘦网2026-11-14【热点】{固定数字1}人已围观
简介小旋风万能蜘蛛池【tg:seogoogle987】
熟悉 c++ 的肯定知道 shared_ptr, unique_ptr, 而 Rust 也有智能指针 Box, Rc, Arc, RefCell 等等,本文分享 Box 底层实现
Box会在堆上分配空间,存储 T 值,并返回对应的指针。同时 Box 也实现了 trait Deref 解引用和 Drop 析构,当 Box 离开作用域时自动释放空间
入门例子
例子来自 the rust book, 为了演示方便,去掉打印语句
fn main() { let _ = Box::new(0x11223344); }
将变量 0x11223344 分配在堆上,所谓的装箱,java 同学肯定很熟悉。让我们挂载 docker, 使用 rust-gdb 查看汇编实现
Dump of&nbs揭开p;assembler code for function hello_cargo::main: 0x000055555555bdb0 <+0>: sub $0x18,%rsp 0x000055555555bdb4 <+4>: movl $0x11223344,0x14(%rsp) => 0x000055555555bdbc <+12>: mov $0x4,%esi&nb智能sp; 0x000055555555bdc1 <+17>: mov %rsi,%rdi 0x000055555555bdc4 <+20>: callq 0x55555555b5b0 <alloc::alloc::exchange_malloc> 0x000055555555bdc9 <+25>: mov %rax,%rcx 0x0000555指针55555bdcc <+28>: mov %rcx,%rax 0x000055555555bdcf <+31>: movl $0x11223344,(%rcx) 0x000055555555bdd5 <+37>: mov %rax,0x8(%rsp) 0x000055555555bdda <+42>: lea 0x8( B%rsp),%rdi 0x000055555555bddf <+47>: callq 0x55555555bd20 <core::ptr::drop_in_place<alloc::boxed::Box>> 0x000055555555bde4 <+52>: add $0x18,%rsp 0x000055555555bde8 <+56>: retq End of assembler&nbsoxp;dump.
关键点就两条,alloc::alloc::exchange_malloc 在堆上分配内存空间,然后将 0x11223344 存储到这个 malloc 的地址上
函数结束时,将地址传递给 core::ptr::drop_in_place 去释放,因为编译器知道类型是 alloc::boxed::Box, 会掉用 Box 相应的 drop 函数
单纯的看这个例子,Box 并不神秘,对应汇编实现,和普通指针没区别,一切约束都是编译期行为
所有权 fn main() { let x = Box::new(String::from("Rust")); let y =&nbs 的p;*x; println!("x is {}", x); }
这个例子中将字符串装箱,其实没必要这么写,因为 String 广义来讲本身就是一种智能指针。这个例子会报错
3 | let y = *x; | -- value moved here 4 | &nbs神秘p;println!("x is {}", x); | ^ value borrowed here after move
*x 解引用后对应 String, 赋值给 y 时执行 move 语义,所有权不在了,所以后续 println 不能打印 x
let y = &*x;
可以取字符串的不面纱可变引用来 fix
底层实现 pub struct Box< T: ?Sized, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global, >(Unique, A);
上面是 Box 的定义,可以看到是一个元组结构体,有两个泛型参数:T 代表任意类型,A 代表内存分配器。标准库里 A 是 Gloal 默认值。其中 T 有一个泛型约束 ?Sized, 表示在编译时可能知道类型大小,也可能不知道,当然一揭开般都用于不知道大小的场景,很少像上文一样存储 int
#[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> { fn drop(&mut self) { // FIXM智能E: Do nothing, drop is currently performed by compiler. } }
这是 Drop 实现,源码里也说了,由编译器实现
#[stable(feature = "rust1", since = "1.0.0")] impl Deref for Box<T, A> { type Target = T; &nb指针sp; fn deref(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] impl DerefMut for Box<T, A> { fn Bderef_mut(&mut self) -> &mut T { &mut **self } }
实现了 Deref 可以定义解引用行为,DerefMut 可变解引用。所以 *x 对应着操作 *(x.deref())
适用场景
官网提到以下三个场景,本质上 Box 和普通指针区别不大,所以用处不如 Rc, Arc, RefCell 广
当类型在编译期不知道大小,但代码场景还要求确认类型大小的时候 当你有大量数据,需要移动所有权,而不想 copy 数据的时候 trait 对象,或者称为 dyn 动态分发常用在ox一个集合中存储不同的类型上,或者参数指定不同的类型
官网有一个链表的实现
enum List { Cons(i32, List), Nil, }
上面代码是无法运行的,道理也很简单,这是一种递归定义。对应 c 代码也是不行的,我们一般要给 next 类型定义成指针才行
enum List { Cons(i32, Box), Nil, } use crate::List::{C 的ons, Nil}; fn main() { let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); }
官网给的解决方案,就是将 next 变成了指针 Box , 算是常识吧,没什么好说的
很赞哦!(36129)
相关文章
- 标签: 海尔智家 卡萨帝 Leader Seeker
- 选择对话式人工智能平台时的四个视角
- OpenAI CEO阿尔特曼:对上市后继续担任CEO持保留态度
- 手把手教你用Pyecharts库对淘宝数据进行可视化展示
- 云安全日报220712:IBM Integration Bus集成解决方案发现执行任意代码漏洞,需要尽快升级
- 微软正式发布 GPT-realtime 模型,主打更逼真语音与多模态输入
- 云计算核心技术Docker教程:将Docker容器映像推送到Docker Hub
- 标签: 马云 阿里巴巴 云谷学校 AI教育
- 标签: 目心智能 TerraMow 安克创新 纯视觉VSLAM
- 标签: 夜巴黎 大河报 DoNews 未成年人直播
站长推荐
友情链接
- 标签: 康师傅
- https://www.nctsn.org/search?cat=191&query=小旋风万能蜘蛛池【tg:seogoogle987】,0MB
- https://www.springfieldlibrary.org/library/?s=小旋风万能蜘蛛池【tg:seogoogle987】,w8h
- https://yscc1986.net/search/小旋风万能蜘蛛池【tg:seogoogle987】01n
- https://www.remit.co.jp/pt/?action=CHECK&s=小旋风万能蜘蛛池【tg:seogoogle987】,T0U
- https://www.mdbg.net/chinese/dictionary?page=worddict&wdrst=0&wdqb=小旋风万能蜘蛛池【tg:seogoogle987】,gMd
- https://www.shopping.com/search.html?keyword=小旋风万能蜘蛛池【tg:seogoogle987】,NPM
- https://www.vet-direct.com/search?cat=72&term=小旋风万能蜘蛛池【tg:seogoogle987】,yDs
- https://www.safetv.go.kr/base/search/view?searchWord=小旋风万能蜘蛛池【tg:seogoogle987】igH
- https://www.varian.com/en-au/search?cat=113&search=小旋风万能蜘蛛池【tg:seogoogle987】,61T
- https://www.lezhin.com/ko/tags/小旋风万能蜘蛛池【tg:seogoogle987】,wNx
- https://www.skicheck.at/en/?action=CHECK&s=小旋风万能蜘蛛池【tg:seogoogle987】,8zU
- https://www.otakuninjahero.com/en/search/小旋风万能蜘蛛池【tg:seogoogle987】,ufE
- https://www.parriscues.com/catalogsearch/result/?q=小旋风万能蜘蛛池【tg:seogoogle987】,suX
- https://www.qidulp.com/search?query=小旋风万能蜘蛛池【tg:seogoogle987】,bPq
- https://www.scivee.tv/?s=小旋风万能蜘蛛池【tg:seogoogle987】,IaS
- https://www.jusoen.com/addreng.asp?p1=小旋风万能蜘蛛池【tg:seogoogle987】UB2
- https://www.paulaschoice.hk/zh_hant/catalogsearch/result/?q=小旋风万能蜘蛛池【tg:seogoogle987】,7BZ
- https://m.shoppinghow.kakao.com/m/search/q/小旋风万能蜘蛛池【tg:seogoogle987】HFI
- https://www.lyrics.com/lyrics/小旋风万能蜘蛛池【tg:seogoogle987】,GZg
- https://www.wellbees.com/catalogsearch/result/?action=CHECK&q=小旋风万能蜘蛛池【tg:seogoogle987】,96F
- https://www.polliwogs.com/search/小旋风万能蜘蛛池【tg:seogoogle987】,TjL
- https://www.vocabulary.com/dictionary/小旋风万能蜘蛛池【tg:seogoogle987】,iXe
- https://www.vietnamconsulate-sf.org/?action=CHECK&s=小旋风万能蜘蛛池【tg:seogoogle987】,0YL
- https://5gaa.org/?token=6e2l7hjt2i26gzgctgwdrv7v0j6nxorq&s=小旋风万能蜘蛛池【tg:seogoogle987】sL9
- https://www.lyrics.com/lyrics/kkk3小旋风万能蜘蛛池【tg:seogoogle987】,u6s
- https://www.vfw.org/search-results?q=小旋风万能蜘蛛池【tg:seogoogle987】,3gj
- https://www.ucycle.com/search/=小旋风万能蜘蛛池【tg:seogoogle987】,VmR
- https://www.impactpool.org/search/?type=79&q=小旋风万能蜘蛛池【tg:seogoogle987】FU8
- https://www.so.com/s?ie=utf-8&src=360sou_home&_re=0&q=小旋风万能蜘蛛池【tg:seogoogle987】,Iuj
- https://www.teamlab.art/?submit=小旋风万能蜘蛛池【tg:seogoogle987】,hDf
- https://www.mynextmove.org/find/search?s=小旋风万能蜘蛛池【tg:seogoogle987】,NUh
- https://www.riohondo.edu/?action=QUERY&s=小旋风万能蜘蛛池【tg:seogoogle987】,Lj2
- https://www.temu.com/search_result.html?search_key=小旋风万能蜘蛛池【tg:seogoogle987】rOb
- https://www.roberthalf.com/us/en/jobs/all/小旋风万能蜘蛛池【tg:seogoogle987】elq
- https://www.olx.ba/pretraga?trazilica=小旋风万能蜘蛛池【tg:seogoogle987】,lxT
- https://www.remit.co.jp/vi/?s=小旋风万能蜘蛛池【tg:seogoogle987】c9K
- https://www.tullygroup.us/?ID=hbkq8jFjrQlVRrwzEmvoUJJAY4e1Lfo5&s=小旋风万能蜘蛛池【tg:seogoogle987】,rGu
- https://www.msrenewal.com/search/小旋风万能蜘蛛池【tg:seogoogle987】,T1l
- https://www.youtube.com/hashtag/小旋风万能蜘蛛池【tg:seogoogle987】,dD0
- https://www.world-architects.com/en/search?term=小旋风万能蜘蛛池【tg:seogoogle987】,Lbr
- https://www.therapeuticassociates.com/?cat=5&s=小旋风万能蜘蛛池【tg:seogoogle987】,zld
- https://www.nytimes.com/search?dropmab=true&query=小旋风万能蜘蛛池【tg:seogoogle987】,PhZ
- https://www.kubb-tool.bfs.admin.ch/en/search?action=CHECK&q=小旋风万能蜘蛛池【tg:seogoogle987】,fuf
- https://www.wellbees.com/index.php/catalogsearch/result/index/?q=小旋风万能蜘蛛池【tg:seogoogle987】,LRw
- https://www.spicebar.de/catalogsearch/result/?q=小旋风万能蜘蛛池【tg:seogoogle987】,eDw
- https://www.terramania.nl/catalogsearch/result/index/?q=小旋风万能蜘蛛池【tg:seogoogle987】,G17
- https://www.resilienz-akademie.com/?cat=71&s=小旋风万能蜘蛛池【tg:seogoogle987】,pOG
- https://www.zutari.com/?s=小旋风万能蜘蛛池【tg:seogoogle987】,92c
- https://www.woorden.org/spreekwoord.php?woord=小旋风万能蜘蛛池【tg:seogoogle987】,RLH
- https://www.parl.ca/legisinfo/fr/projets-de-loi?parlsession=all&view=list&keywords=小旋风万能蜘蛛池【tg:seogoogle987】,KkD







