知识卡片

普通读书笔记卡 · 1441.d · 生成模型:未记录

所有者离域触发析构

理解等级:中级

值由拥有它的变量负责。只要值仍由该变量拥有,当其释放作用域结束,Rust 会运行相应析构。String 将堆缓冲归还给分配器。已移出的值由新所有者清理,这种以持有对象约束资源释放的方式也可用于锁守卫。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 理解所有权 What Is Ownership? · 查看原书依据

      There is a natural point at which we can return the memory our String needs to the allocator: when s goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called drop, and it’s where the author of String can put the code to return the memory. Rust calls drop automatically at the closing curly bracket.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第04章 理解所有权(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c04.xhtml`,块 0050) - 结论依据:String 在作用域末尾调用 drop 归还申请的空间,原文将其联系到 RAII。 - 原始内容:There is a natural point at which we can return the memory our String needs to the allocator: when s goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called drop, and it’s where the author of String can put the code to return the memory. Rust calls drop automatically at the closing curly bracket.