<!DOCTYPE HTML>
< html lang = "zh-CN" class = "light sidebar-visible" dir = "ltr" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
< title > Weak 与循环引用 - Rust语言圣经(Rust Course)< / title >
<!-- Custom HTML head -->
< meta name = "description" content = "" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< meta name = "theme-color" content = "#ffffff" >
< link rel = "icon" href = "../../favicon-de23e50b.svg" >
< link rel = "shortcut icon" href = "../../favicon-8114d1fc.png" >
< link rel = "stylesheet" href = "../../css/variables-8adf115d.css" >
< link rel = "stylesheet" href = "../../css/general-2459343d.css" >
< link rel = "stylesheet" href = "../../css/chrome-ae938929.css" >
< link rel = "stylesheet" href = "../../css/print-9e4910d8.css" media = "print" >
<!-- Fonts -->
< link rel = "stylesheet" href = "../../fonts/fonts-9644e21d.css" >
<!-- Highlight.js Stylesheets -->
< link rel = "stylesheet" id = "mdbook-highlight-css" href = "../../highlight-493f70e1.css" >
< link rel = "stylesheet" id = "mdbook-tomorrow-night-css" href = "../../tomorrow-night-4c0ae647.css" >
< link rel = "stylesheet" id = "mdbook-ayu-highlight-css" href = "../../ayu-highlight-3fdfc3ac.css" >
<!-- Custom theme stylesheets -->
< link rel = "stylesheet" href = "../../theme/style-78591068.css" >
<!-- Provide site root and default themes to javascript -->
< script >
const path_to_root = "../../";
const default_light_theme = "light";
const default_dark_theme = "navy";
window.path_to_searchindex_js = "../../searchindex-4a1a74fa.js";
< / script >
<!-- Start loading toc.js asap -->
< script src = "../../toc-42887675.js" > < / script >
< / head >
< body >
< div id = "mdbook-help-container" >
< div id = "mdbook-help-popup" >
< h2 class = "mdbook-help-title" > Keyboard shortcuts< / h2 >
< div >
< p > Press < kbd > ←< / kbd > or < kbd > →< / kbd > to navigate between chapters< / p >
< p > Press < kbd > S< / kbd > or < kbd > /< / kbd > to search in the book< / p >
< p > Press < kbd > ?< / kbd > to show this help< / p >
< p > Press < kbd > Esc< / kbd > to hide this help< / p >
< / div >
< / div >
< / div >
< div id = "mdbook-body-container" >
<!-- Work around some values being stored in localStorage wrapped in quotes -->
< script >
try {
let theme = localStorage.getItem('mdbook-theme');
let sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') & & theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') & & sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
< / script >
<!-- Set the theme before any content is loaded, prevents flash -->
< script >
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
< / script >
< input type = "checkbox" id = "mdbook-sidebar-toggle-anchor" class = "hidden" >
<!-- Hide / unhide sidebar before it is displayed -->
< script >
let sidebar = null;
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
sidebar_toggle.checked = false;
}
if (sidebar === 'visible') {
sidebar_toggle.checked = true;
} else {
html.classList.remove('sidebar-visible');
}
< / script >
< nav id = "mdbook-sidebar" class = "sidebar" aria-label = "Table of contents" >
<!-- populated by js -->
< mdbook-sidebar-scrollbox class = "sidebar-scrollbox" > < / mdbook-sidebar-scrollbox >
< noscript >
< iframe class = "sidebar-iframe-outer" src = "../../toc.html" > < / iframe >
< / noscript >
< div id = "mdbook-sidebar-resize-handle" class = "sidebar-resize-handle" >
< div class = "sidebar-resize-indicator" > < / div >
< / div >
< / nav >
< div id = "mdbook-page-wrapper" class = "page-wrapper" >
< div class = "page" >
< div id = "mdbook-menu-bar-hover-placeholder" > < / div >
< div id = "mdbook-menu-bar" class = "menu-bar sticky" >
< div class = "left-buttons" >
< label id = "mdbook-sidebar-toggle" class = "icon-button" for = "mdbook-sidebar-toggle-anchor" title = "Toggle Table of Contents" aria-label = "Toggle Table of Contents" aria-controls = "mdbook-sidebar" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 448 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z" / > < / svg > < / span >
< / label >
< button id = "mdbook-theme-toggle" class = "icon-button" type = "button" title = "Change theme" aria-label = "Change theme" aria-haspopup = "true" aria-expanded = "false" aria-controls = "mdbook-theme-list" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 576 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z" / > < / svg > < / span >
< / button >
< ul id = "mdbook-theme-list" class = "theme-popup" aria-label = "Themes" role = "menu" >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-default_theme" > Auto< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-light" > Light< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-rust" > Rust< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-coal" > Coal< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-navy" > Navy< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-ayu" > Ayu< / button > < / li >
< / ul >
< button id = "mdbook-search-toggle" class = "icon-button" type = "button" title = "Search (`/`)" aria-label = "Toggle Searchbar" aria-expanded = "false" aria-keyshortcuts = "/ s" aria-controls = "mdbook-searchbar" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z" / > < / svg > < / span >
< / button >
< / div >
< h1 class = "menu-title" > Rust语言圣经(Rust Course)< / h1 >
< div class = "right-buttons" >
< a href = "../../print.html" title = "Print this book" aria-label = "Print this book" >
< span class = fa-svg id = "print-button" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z" / > < / svg > < / span >
< / a >
< a href = "https://github.com/sunface/rust-course" title = "Git repository" aria-label = "Git repository" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 496 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z" / > < / svg > < / span >
< / a >
< a href = "https://github.com/sunface/rust-course/edit/main/src/advance/circle-self-ref/circle-reference.md" title = "Suggest an edit" aria-label = "Suggest an edit" rel = "edit" >
< span class = fa-svg id = "git-edit-button" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M421.7 220.3l-11.3 11.3-22.6 22.6-205 205c-6.6 6.6-14.8 11.5-23.8 14.1L30.8 511c-8.4 2.5-17.5 .2-23.7-6.1S-1.5 489.7 1 481.2L38.7 353.1c2.6-9 7.5-17.2 14.1-23.8l205-205 22.6-22.6 11.3-11.3 33.9 33.9 62.1 62.1 33.9 33.9zM96 353.9l-9.3 9.3c-.9 .9-1.6 2.1-2 3.4l-25.3 86 86-25.3c1.3-.4 2.5-1.1 3.4-2l9.3-9.3H112c-8.8 0-16-7.2-16-16V353.9zM453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-14.5 14.5-22.6 22.6-11.3 11.3-33.9-33.9-62.1-62.1L314.3 67.7l11.3-11.3 22.6-22.6 14.5-14.5c25-25 65.5-25 90.5 0z" / > < / svg > < / span >
< / a >
< / div >
< / div >
< div id = "mdbook-search-wrapper" class = "hidden" >
< form id = "mdbook-searchbar-outer" class = "searchbar-outer" >
< div class = "search-wrapper" >
< input type = "search" id = "mdbook-searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "mdbook-searchresults-outer" aria-describedby = "searchresults-header" >
< div class = "spinner-wrapper" >
< span class = fa-svg id = "fa-spin" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z" / > < / svg > < / span >
< / div >
< / div >
< / form >
< div id = "mdbook-searchresults-outer" class = "searchresults-outer hidden" >
< div id = "mdbook-searchresults-header" class = "searchresults-header" > < / div >
< ul id = "mdbook-searchresults" >
< / ul >
< / div >
< / div >
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
< script >
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
< / script >
< div id = "mdbook-content" class = "content" >
< main >
< h1 id = "weak-与循环引用" > < a class = "header" href = "#weak-与循环引用" > Weak 与循环引用< / a > < / h1 >
< p > Rust 的安全性是众所周知的,但是不代表它不会内存泄漏。一个典型的例子就是同时使用 < code > Rc< T> < / code > 和 < code > RefCell< T> < / code > 创建循环引用,最终这些引用的计数都无法被归零,因此 < code > Rc< T> < / code > 拥有的值也不会被释放清理。< / p >
< h2 id = "何为循环引用" > < a class = "header" href = "#何为循环引用" > 何为循环引用< / a > < / h2 >
< p > 关于内存泄漏,如果你没有充足的 Rust 经验,可能都无法造出一份代码来再现它:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
enum List {
Cons(i32, RefCell< Rc< List> > ),
Nil,
}
impl List {
fn tail(& self) -> Option< & RefCell< Rc< List> > > {
match self {
Cons(_, item) => Some(item),
Nil => None,
}
}
}
fn main() {}< / code > < / pre >
< p > 这里我们创建一个有些复杂的枚举类型 < code > List< / code > ,这个类型很有意思,它的每个值都指向了另一个 < code > List< / code > ,此外,得益于 < code > Rc< / code > 的使用还允许多个值指向一个 < code > List< / code > : < / p >
< img alt = "" src = "https://pica.zhimg.com/80/v2-0db007dfb4167ebc22f50cf5b5a85f53_1440w.png" class = "center" / >
< p > 如上图所示,每个矩形框节点都是一个 < code > List< / code > 类型,它们或者是拥有值且指向另一个 < code > List< / code > 的< code > Cons< / code > ,或者是一个没有值的终结点 < code > Nil< / code > 。同时,由于 < code > RefCell< / code > 的使用,每个 < code > List< / code > 所指向的 < code > List< / code > 还能够被修改。< / p >
< p > 下面来使用一下这个复杂的 < code > List< / code > 枚举:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
println!("a的初始化rc计数 = {}", Rc::strong_count(& a));
println!("a指向的节点 = {:?}", a.tail());
// 创建`b`到`a`的引用
let b = Rc::new(Cons(10, RefCell::new(Rc::clone(& a))));
println!("在b创建后, a的rc计数 = {}", Rc::strong_count(& a));
println!("b的初始化rc计数 = {}", Rc::strong_count(& b));
println!("b指向的节点 = {:?}", b.tail());
// 利用RefCell的可变性, 创建了`a`到`b`的引用
if let Some(link) = a.tail() {
*link.borrow_mut() = Rc::clone(& b);
}
println!("在更改a后, b的rc计数 = {}", Rc::strong_count(& b));
println!("在更改a后, a的rc计数 = {}", Rc::strong_count(& a));
// 下面一行println!将导致循环引用
// 我们可怜的8MB大小的main线程栈空间将被它冲垮, 最终造成栈溢出
// println!("a next item = {:?}", a.tail());
}< / code > < / pre >
< p > 这个类型定义看着复杂,使用起来更复杂!不过排除这些因素,我们可以清晰看出:< / p >
< ol >
< li > 在创建了 < code > a< / code > 后,紧接着就使用 < code > a< / code > 创建了 < code > b< / code > ,因此 < code > b< / code > 引用了 < code > a< / code > < / li >
< li > 然后我们又利用 < code > Rc< / code > 克隆了 < code > b< / code > ,然后通过 < code > RefCell< / code > 的可变性,让 < code > a< / code > 引用了 < code > b< / code > < / li >
< / ol >
< p > 至此我们成功创建了循环引用< code > a< / code > -> < code > b< / code > -> < code > a< / code > -> < code > b< / code > ····< / p >
< p > 先来观察下引用计数:< / p >
< pre > < code class = "language-console" > a的初始化rc计数 = 1
a指向的节点 = Some(RefCell { value: Nil })
在b创建后, a的rc计数 = 2
b的初始化rc计数 = 1
b指向的节点 = Some(RefCell { value: Cons(5, RefCell { value: Nil }) })
在更改a后, b的rc计数 = 2
在更改a后, a的rc计数 = 2
< / code > < / pre >
< p > 在 < code > main< / code > 函数结束前,< code > a< / code > 和 < code > b< / code > 的引用计数均是 < code > 2< / code > ,随后 < code > b< / code > 触发 < code > Drop< / code > ,此时引用计数会变为 < code > 1< / code > ,并不会归 < code > 0< / code > ,因此 < code > b< / code > 所指向内存不会被释放,同理可得 < code > a< / code > 指向的内存也不会被释放,最终发生了内存泄漏。< / p >
< p > 下面一张图很好的展示了这种引用循环关系:
< img alt = "" src = "https://pic1.zhimg.com/80/v2-2dbfc981f05019bf70bf81c93f956c35_1440w.png" class = "center" / > < / p >
< p > 现在我们还需要轻轻的推一下,让塔米诺骨牌轰然倒塌。反注释最后一行代码,试着运行下:< / p >
< pre > < code class = "language-console" > RefCell { value: Cons(5, RefCell { value: Cons(10, RefCell { value: Cons(5, RefCell { value: Cons(10, RefCell { value: Cons(5, RefCell { value: Cons(10, RefCell {
...无穷无尽
thread 'main' has overflowed its stack
fatal runtime error: stack overflow
< / code > < / pre >
< p > 通过 < code > a.tail< / code > 的调用, Rust 试图打印出 < code > a -> b -> a ···< / code > 的所有内容,但是在不懈的努力后,< code > main< / code > 线程终于不堪重负,发生了< a href = "https://course.rs/pitfalls/stack-overflow.html" > 栈溢出< / a > 。< / p >
< p > 以上的代码可能并不会造成什么大的问题,但是在一个更加复杂的程序中,类似的问题可能会造成你的程序不断地分配内存、泄漏内存,最终程序会不幸< strong > OOM< / strong > ,当然这其中的 CPU 损耗也不可小觑。< / p >
< p > 总之,创建循环引用并不简单,但是也并不是完全遇不到,当你使用 < code > RefCell< Rc< T> > < / code > 或者类似的类型嵌套组合(具备内部可变性和引用计数)时,就要打起万分精神,前面可能是深渊!< / p >
< p > 那么问题来了? 如果我们确实需要实现上面的功能,该怎么办?答案是使用 < code > Weak< / code > 。< / p >
< h2 id = "weak" > < a class = "header" href = "#weak" > Weak< / a > < / h2 >
< p > < code > Weak< / code > 非常类似于 < code > Rc< / code > ,但是与 < code > Rc< / code > 持有所有权不同,< code > Weak< / code > 不持有所有权,它仅仅保存一份指向数据的弱引用:如果你想要访问数据,需要通过 < code > Weak< / code > 指针的 < code > upgrade< / code > 方法实现,该方法返回一个类型为 < code > Option< Rc< T> > < / code > 的值。< / p >
< p > 看到这个返回,相信大家就懂了:何为弱引用?就是< strong > 不保证引用关系依然存在< / strong > ,如果不存在,就返回一个 < code > None< / code > ! < / p >
< p > 因为 < code > Weak< / code > 引用不计入所有权,因此它< strong > 无法阻止所引用的内存值被释放掉< / strong > ,而且 < code > Weak< / code > 本身不对值的存在性做任何担保,引用的值还存在就返回 < code > Some< / code > ,不存在就返回 < code > None< / code > 。< / p >
< h4 id = "weak-与-rc-对比" > < a class = "header" href = "#weak-与-rc-对比" > Weak 与 Rc 对比< / a > < / h4 >
< p > 我们来将 < code > Weak< / code > 与 < code > Rc< / code > 进行以下简单对比:< / p >
< div class = "table-wrapper" >
< table >
< thead >
< tr > < th > < code > Weak< / code > < / th > < th > < code > Rc< / code > < / th > < / tr >
< / thead >
< tbody >
< tr > < td > 不计数< / td > < td > 引用计数< / td > < / tr >
< tr > < td > 不拥有所有权< / td > < td > 拥有值的所有权< / td > < / tr >
< tr > < td > 不阻止值被释放(drop)< / td > < td > 所有权计数归零,才能 drop< / td > < / tr >
< tr > < td > 引用的值存在返回 < code > Some< / code > ,不存在返回 < code > None < / code > < / td > < td > 引用的值必定存在< / td > < / tr >
< tr > < td > 通过 < code > upgrade< / code > 取到 < code > Option< Rc< T> > < / code > ,然后再取值< / td > < td > 通过 < code > Deref< / code > 自动解引用,取值无需任何操作< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 通过这个对比,可以非常清晰的看出 < code > Weak< / code > 为何这么弱,而这种弱恰恰非常适合我们实现以下的场景:< / p >
< ul >
< li > 持有一个 < code > Rc< / code > 对象的临时引用,并且不在乎引用的值是否依然存在< / li >
< li > 阻止 < code > Rc< / code > 导致的循环引用,因为 < code > Rc< / code > 的所有权机制,会导致多个 < code > Rc< / code > 都无法计数归零< / li >
< / ul >
< p > 使用方式简单总结下:< strong > 对于父子引用关系,可以让父节点通过 < code > Rc< / code > 来引用子节点,然后让子节点通过 < code > Weak< / code > 来引用父节点< / strong > 。< / p >
< h4 id = "weak-总结" > < a class = "header" href = "#weak-总结" > Weak 总结< / a > < / h4 >
< p > 因为 < code > Weak< / code > 本身并不是很好理解,因此我们再来帮大家梳理总结下,然后再通过一个例子,来彻底掌握。< / p >
< p > < code > Weak< / code > 通过 < code > use std::rc::Weak< / code > 来引入,它具有以下特点:< / p >
< ul >
< li > 可访问,但没有所有权,不增加引用计数,因此不会影响被引用值的释放回收< / li >
< li > 可由 < code > Rc< T> < / code > 调用 < code > downgrade< / code > 方法转换成 < code > Weak< T> < / code > < / li >
< li > < code > Weak< T> < / code > 可使用 < code > upgrade< / code > 方法转换成 < code > Option< Rc< T> > < / code > ,如果资源已经被释放,则 < code > Option< / code > 的值是 < code > None< / code > < / li >
< li > 常用于解决循环引用的问题< / li >
< / ul >
< p > 一个简单的例子:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::rc::Rc;
fn main() {
// 创建Rc, 持有一个值5
let five = Rc::new(5);
// 通过Rc, 创建一个Weak指针
let weak_five = Rc::downgrade(& five);
// Weak引用的资源依然存在, 取到值5
let strong_five: Option< Rc< _> > = weak_five.upgrade();
assert_eq!(*strong_five.unwrap(), 5);
// 手动释放资源`five`
drop(five);
// Weak引用的资源已不存在, 因此返回None
let strong_five: Option< Rc< _> > = weak_five.upgrade();
assert_eq!(strong_five, None);
}< / code > < / pre >
< p > 需要承认的是,使用 < code > Weak< / code > 让 Rust 本来就堪忧的代码可读性又下降了不少,但是。。。真香,因为可以解决循环引用了。< / p >
< h2 id = "使用-weak-解决循环引用" > < a class = "header" href = "#使用-weak-解决循环引用" > 使用 Weak 解决循环引用< / a > < / h2 >
< p > 理论知识已经足够,现在用两个例子来模拟下真实场景下可能会遇到的循环引用。< / p >
< h4 id = "工具间的故事" > < a class = "header" href = "#工具间的故事" > 工具间的故事< / a > < / h4 >
< p > 工具间里,每个工具都有其主人,且多个工具可以拥有一个主人;同时一个主人也可以拥有多个工具,在这种场景下,就很容易形成循环引用,好在我们有 < code > Weak< / code > : < / p >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::rc::Rc;
use std::rc::Weak;
use std::cell::RefCell;
// 主人
struct Owner {
name: String,
gadgets: RefCell< Vec< Weak< Gadget> > > ,
}
// 工具
struct Gadget {
id: i32,
owner: Rc< Owner> ,
}
fn main() {
// 创建一个 Owner
// 需要注意,该 Owner 也拥有多个 `gadgets`
let gadget_owner : Rc< Owner> = Rc::new(
Owner {
name: "Gadget Man".to_string(),
gadgets: RefCell::new(Vec::new()),
}
);
// 创建工具,同时与主人进行关联:创建两个 gadget, 他们分别持有 gadget_owner 的一个引用。
let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
// 为主人更新它所拥有的工具
// 因为之前使用了 `Rc`,现在必须要使用 `Weak`,否则就会循环引用
gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(& gadget1));
gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(& gadget2));
// 遍历 gadget_owner 的 gadgets 字段
for gadget_opt in gadget_owner.gadgets.borrow().iter() {
// gadget_opt 是一个 Weak< Gadget> 。 因为 weak 指针不能保证他所引用的对象
// 仍然存在。所以我们需要显式的调用 upgrade() 来通过其返回值(Option< _> )来判
// 断其所指向的对象是否存在。
// 当然, Option 为 None 的时候这个引用原对象就不存在了。
let gadget = gadget_opt.upgrade().unwrap();
println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
}
// 在 main 函数的最后, gadget_owner, gadget1 和 gadget2 都被销毁。
// 具体是,因为这几个结构体之间没有了强引用(`Rc< T> `),所以,当他们销毁的时候。
// 首先 gadget2 和 gadget1 被销毁。
// 然后因为 gadget_owner 的引用数量为 0, 所以这个对象可以被销毁了。
// 循环引用问题也就避免了
}< / code > < / pre >
< h4 id = "tree-数据结构" > < a class = "header" href = "#tree-数据结构" > tree 数据结构< / a > < / h4 >
< pre class = "playground" > < code class = "language-rust edition2021" > use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[derive(Debug)]
struct Node {
value: i32,
parent: RefCell< Weak< Node> > ,
children: RefCell< Vec< Rc< Node> > > ,
}
fn main() {
let leaf = Rc::new(Node {
value: 3,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(& leaf),
Rc::weak_count(& leaf),
);
{
let branch = Rc::new(Node {
value: 5,
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(& leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(& branch);
println!(
"branch strong = {}, weak = {}",
Rc::strong_count(& branch),
Rc::weak_count(& branch),
);
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(& leaf),
Rc::weak_count(& leaf),
);
}
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade());
println!(
"leaf strong = {}, weak = {}",
Rc::strong_count(& leaf),
Rc::weak_count(& leaf),
);
}
< / code > < / pre >
< p > 这个例子就留给读者自己解读和分析,我们就不画蛇添足了:) < / p >
< h2 id = "unsafe-解决循环引用" > < a class = "header" href = "#unsafe-解决循环引用" > unsafe 解决循环引用< / a > < / h2 >
< p > 除了使用 Rust 标准库提供的这些类型,你还可以使用 < code > unsafe< / code > 里的裸指针来解决这些棘手的问题,但是由于我们还没有讲解 < code > unsafe< / code > ,因此这里就不进行展开,只附上< a href = "https://github.com/sunface/rust-algos/blob/fbcdccf3e8178a9039329562c0de0fd01a3372fb/src/unsafe/self-ref.md" > 源码链接< / a > ,挺长的,需要耐心 o_o< / p >
< p > 虽然 < code > unsafe< / code > 不安全,但是在各种库的代码中依然很常见用它来实现自引用结构,主要优点如下:< / p >
< ul >
< li > 性能高,毕竟直接用裸指针操作< / li >
< li > 代码更简单更符合直觉: 对比下 < code > Option< Rc< RefCell< Node> > > < / code > < / li >
< / ul >
< h2 id = "总结" > < a class = "header" href = "#总结" > 总结< / a > < / h2 >
< p > 本文深入讲解了何为循环引用以及如何使用 < code > Weak< / code > 来解决,同时还结合 < code > Rc< / code > 、< code > RefCell< / code > 、< code > Weak< / code > 等实现了两个有实战价值的例子,让大家对智能指针的使用更加融会贯通。< / p >
< p > 至此,智能指针一章即将结束(严格来说还有一个 < code > Mutex< / code > 放在多线程一章讲解),而 Rust 语言本身的学习之旅也即将结束,后面我们将深入多线程、项目工程、应用实践、性能分析等特色专题,来一睹 Rust 在这些领域的风采。< / p >
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
< a rel = "prev" href = "../../advance/circle-self-ref/intro.html" class = "mobile-nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z" / > < / svg > < / span >
< / a >
< a rel = "next prefetch" href = "../../advance/circle-self-ref/self-referential.html" class = "mobile-nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z" / > < / svg > < / span >
< / a >
< div style = "clear: both" > < / div >
< / nav >
< / div >
< / div >
< nav class = "nav-wide-wrapper" aria-label = "Page navigation" >
< a rel = "prev" href = "../../advance/circle-self-ref/intro.html" class = "nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z" / > < / svg > < / span >
< / a >
< a rel = "next prefetch" href = "../../advance/circle-self-ref/self-referential.html" class = "nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z" / > < / svg > < / span >
< / a >
< / nav >
< / div >
< template id = fa-eye > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 576 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z" / > < / svg > < / span > < / template >
< template id = fa-eye-slash > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 640 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z" / > < / svg > < / span > < / template >
< template id = fa-copy > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z" / > < / svg > < / span > < / template >
< template id = fa-play > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 384 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z" / > < / svg > < / span > < / template >
< template id = fa-clock-rotate-left > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z" / > < / svg > < / span > < / template >
< script >
window.playground_copyable = true;
< / script >
< script src = "../../ace-2a3cd908.js" > < / script >
< script src = "../../mode-rust-2c9d5c9a.js" > < / script >
< script src = "../../editor-16ca416c.js" > < / script >
< script src = "../../theme-dawn-4493f9c8.js" > < / script >
< script src = "../../theme-tomorrow_night-9dbe62a9.js" > < / script >
< script src = "../../elasticlunr-ef4e11c1.min.js" > < / script >
< script src = "../../mark-09e88c2c.min.js" > < / script >
< script src = "../../searcher-c2a407aa.js" > < / script >
< script src = "../../clipboard-1626706a.min.js" > < / script >
< script src = "../../highlight-abc7f01d.js" > < / script >
< script src = "../../book-a0b12cfe.js" > < / script >
<!-- Custom JS scripts -->
< script src = "../../assets/custom-7d8ae1df.js" > < / script >
< script src = "../../assets/bigPicture-be03f9c8.js" > < / script >
< / div >
< / body >
< / html >