知识卡片

普通读书笔记卡 · 6074.f.9.d

泄漏换长寿引用有资源代价

理解等级:中级

Box::leak消费Box并交出内部值引用,使它不再按原拥有者作用域自动析构;满足相应类型条件时可得到’static引用。代价是自动回收责任消失,可能形成永久泄漏。它展示内存安全与资源不泄漏的区别,不应作为普通生命周期错误的通用修复。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 3. Concepts The 'static Lifetime · 查看原书依据

      Box::leak function converts an owned Box<T> to a mutable reference to T. There’s no longer an owner for the value, so it can never be dropped—which satisfies the requirements for the 'static lifetime: { let boxed = Box::new(Item { contents: 12 }); // `leak()` consumes the `Box<T>` and returns `&mut T`. let r: &'static Item = Box::leak(boxed); println!("'stat

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《The 'static Lifetime》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u083-ch03-009)。 - 结论依据:原文在“Box::leak”附近的定义、例子或代码支撑本卡核心说明:Box::leak消费Box并交出内部值引用,使它不再按原拥有者作用域自动析构;满足相应类型条件时可得到'static引用。边界按已读前提解释;示例未执行。 - 原始内容:Box::leak function converts an owned Box<T> to a mutable reference to T. There’s no longer an owner for the value, so it can never be dropped—which satisfies the requirements for the 'static lifetime: { let boxed = Box::new(Item { contents: 12 }); // `leak()` consumes the `Box<T>` and returns `&mut T`. let r: &'static Item = Box::leak(boxed); println!("'stat