mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:34:52 -06:00
193 lines
16 KiB
HTML
193 lines
16 KiB
HTML
<!DOCTYPE HTML>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>Smart Pointers - The Rust Programming Language</title>
|
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
|
<meta name="description" content="">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
<base href="">
|
|
|
|
<link rel="stylesheet" href="book.css">
|
|
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
|
|
|
<link rel="shortcut icon" href="favicon.png">
|
|
|
|
<!-- Font Awesome -->
|
|
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
|
|
|
<link rel="stylesheet" href="highlight.css">
|
|
<link rel="stylesheet" href="tomorrow-night.css">
|
|
|
|
<!-- MathJax -->
|
|
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
|
|
|
<!-- Fetch JQuery from CDN but have a local fallback -->
|
|
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
|
<script>
|
|
if (typeof jQuery == 'undefined') {
|
|
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
|
}
|
|
</script>
|
|
</head>
|
|
<body class="light">
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
<script type="text/javascript">
|
|
var theme = localStorage.getItem('theme');
|
|
if (theme == null) { theme = 'light'; }
|
|
$('body').removeClass().addClass(theme);
|
|
</script>
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
<script type="text/javascript">
|
|
var sidebar = localStorage.getItem('sidebar');
|
|
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
|
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
|
</script>
|
|
|
|
<div id="sidebar" class="sidebar">
|
|
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html" class="active"><strong>15.</strong> Smart Pointers</a></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Concurrency</a></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust OOP?</a></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns</a></li><li><a href="ch19-00-more-lifetimes.html"><strong>19.</strong> More Lifetimes</a></li><li><a href="ch20-00-advanced-types.html"><strong>20.</strong> Advanced Type System Features</a></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>21.3.</strong> Derivable Traits</a></li><li><a href="appendix-04-nightly-rust.html"><strong>21.4.</strong> Nightly Rust</a></li><li><a href="appendix-05-macros.html"><strong>21.5.</strong> Macros</a></li><li><a href="appendix-06-translation.html"><strong>21.6.</strong> Translations</a></li></ul></li></ul>
|
|
</div>
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
<div class="page">
|
|
<div id="menu-bar" class="menu-bar">
|
|
<div class="left-buttons">
|
|
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
|
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
|
</div>
|
|
|
|
<h1 class="menu-title">The Rust Programming Language</h1>
|
|
|
|
<div class="right-buttons">
|
|
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="content" class="content">
|
|
<a class="header" href="#smart-pointers" name="smart-pointers"><h1>Smart Pointers</h1></a>
|
|
<p>By smart pointers we mean a reference with more characteristics.</p>
|
|
<p>Example of something that doesn't work</p>
|
|
<p>Surprise! Vec and String are technically smart pointers too!</p>
|
|
<p>This chapter is not a comprehensive list, but will give some examples of the
|
|
ones in the standard library.</p>
|
|
<a class="header" href="#boxt" name="boxt"><h2><code>Box<T></code></h2></a>
|
|
<p>Don't use very often in your own code
|
|
Heap allocated
|
|
Express Ownership of a heap allocated thing</p>
|
|
<p>The three situations to use Box</p>
|
|
<ol>
|
|
<li>Trait objects</li>
|
|
<li>Recursive data structures</li>
|
|
<li>Extend the lifetime of something</li>
|
|
</ol>
|
|
<p>How this interacts with the Drop trait</p>
|
|
<a class="header" href="#rct" name="rct"><h2><code>Rc<T></code></h2></a>
|
|
<p>Reference counted. Rc is for <em>multiple ownership</em> - this thing should get
|
|
deallocated when all of the owners go out of scope.</p>
|
|
<p>Show the data structure:</p>
|
|
<pre><code class="language-rust">struct Rc<T> {
|
|
data: Box<T>,
|
|
strong_reference_count: usize,
|
|
weak_reference_count: usize,
|
|
}
|
|
</code></pre>
|
|
<p>Talk through this.</p>
|
|
<p>This only works if the data is immutable.</p>
|
|
<p>What happens when you clone an Rc: data isn't cloned, increase the strong count.
|
|
When an Rc clone goes out of scope, the count goes down.</p>
|
|
<a class="header" href="#rc-cycles" name="rc-cycles"><h3>Rc Cycles</h3></a>
|
|
<p>This is how you leak memory in rust, which btw is totally safe.</p>
|
|
<p>Is this garbage collecting? Well it's not tracing GC... if you use Rc and had
|
|
a cycle detector, it would be functionally equivalent to a tracing GC. Different
|
|
runtime characteristics tho.</p>
|
|
<a class="header" href="#solution-turn-an-rc-into-a-weakt" name="solution-turn-an-rc-into-a-weakt"><h4>Solution: turn an Rc into a <code>Weak<T></code></h4></a>
|
|
<p>Same as Rc, but doesn't count towards the strong ref count. When you do this, the
|
|
strong ref count goes down and the weak count goes up.</p>
|
|
<p>Data gets cleaned up when the strong count is 0, no matter what the weak count is.
|
|
However, Rc structure is kept until weak reference count also goes to zero, so weak pointers do not become dangling pointers.
|
|
At this point, attempt to upgrade Weak pointer will result into None.
|
|
Only when weak reference counter also reduces to zero, Rc structure is freed.</p>
|
|
<a class="header" href="#refcellt" name="refcellt"><h2><code>RefCell<T></code></h2></a>
|
|
<p>Single owner of mutable data</p>
|
|
<p>The ownership rules checked at runtime instead of compile time.</p>
|
|
<p>Only single threaded. See next chapter.</p>
|
|
<a class="header" href="#borrow-and-borrow_mut-methods" name="borrow-and-borrow_mut-methods"><h3><code>borrow</code> and <code>borrow_mut</code> methods</h3></a>
|
|
<p>Checks all the rules and panics at runtime if the code violates them.</p>
|
|
<ol>
|
|
<li>
|
|
<p>The borrow checker is conservative and people can know more things. (no you
|
|
don't, but if you really want to go back to debugging segfaults, feel free)</p>
|
|
</li>
|
|
<li>
|
|
<p>For when you're only allowed to have an immutable thing (which could be <code>Rc</code>)
|
|
but you need to be able to mutate the underlying data.</p>
|
|
</li>
|
|
</ol>
|
|
<a class="header" href="#cellt" name="cellt"><h2><code>Cell<T></code></h2></a>
|
|
<p>Same thing as RefCell but for types that are Copy. No borrow checking rules here
|
|
anyway. So just reason #2 above.</p>
|
|
<a class="header" href="#is-this-really-safe-yes" name="is-this-really-safe-yes"><h2>Is this really safe? Yes!</h2></a>
|
|
<p>RefCell is still doing the checks, just at runtime
|
|
Cell is safe bc Copy types don't need the ownership rules anyway</p>
|
|
<a class="header" href="#the-interior-mutability-pattern" name="the-interior-mutability-pattern"><h3>The Interior Mutability Pattern</h3></a>
|
|
<p>The Interior Mutability Pattern is super unsafe internally but safe to use
|
|
from the outside and is totally safe, totally, trust us, seriously, it's safe.</p>
|
|
<p>Allude to <code>UnsafeCell<T></code> maybe. Affects optimizations since &mut T is unique.
|
|
UnsafeCell turns off those optimizations so that everything doesn't break.</p>
|
|
<p>This is how you can opt-out of the default of Rust's ownership rules and opt
|
|
in to different guarantees.</p>
|
|
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
|
<p>If you want to implement your own smart pointer, go read the Nomicon.</p>
|
|
<p>Now let's talk about concurrency, and some smart pointers that can be used
|
|
with multiple threads.</p>
|
|
|
|
</div>
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
<a href="ch14-05-extending-cargo.html" class="mobile-nav-chapters previous">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
|
|
|
|
<a href="ch16-00-concurrency.html" class="mobile-nav-chapters next">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<a href="ch14-05-extending-cargo.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
|
<i class="fa fa-angle-left"></i>
|
|
</a>
|
|
|
|
|
|
|
|
<a href="ch16-00-concurrency.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
|
<i class="fa fa-angle-right"></i>
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<!-- Local fallback for Font Awesome -->
|
|
<script>
|
|
if ($(".fa").css("font-family") !== "FontAwesome") {
|
|
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
|
}
|
|
</script>
|
|
|
|
<!-- Livereload script (if served using the cli tool) -->
|
|
|
|
|
|
<script src="highlight.js"></script>
|
|
<script src="book.js"></script>
|
|
</body>
|
|
</html>
|