Skip to content

Commit 1ea7d12

Browse files
committed
pointer guide, rc and arc
1 parent 5fb2dfa commit 1ea7d12

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

src/doc/guide-pointers.md

+44-2
Original file line numberDiff line numberDiff line change
@@ -625,11 +625,53 @@ See [Returning Pointers](#returning-pointers) below for more.
625625

626626
# Rc and Arc
627627

628-
This part is coming soon.
628+
The `Rc<T>` and `Arc<T>` types are related, but not identical. They are useful
629+
for having multiple owners for a bit of immutable data.
630+
631+
They get their names from **reference counted**, which is a name for the
632+
strategy they use to deal with multiple owners. "Reference counting" is a
633+
method where you count the number of times something is referenced. When it
634+
drops to zero, you know that you can deallocate a resource.
635+
636+
`Rc<T>` is named 'arr cee' after the first two letters of 'reference counting.'
637+
`Arc<T>` (said like 'ark') provides an 'atomic reference count'ed type. The
638+
difference is that `Arc<T>` is threadsafe, but more expensive when updating the
639+
count. The types are otherwise identical, and so we'll just talk about `Arc<T>`
640+
for the rest of this section.
641+
642+
You can use the `clone()` method to get an additional reference to an `Arc<T>`.
643+
This method hands out another reference to its data, and then increments the
644+
count. When each reference goes out of scope, it decreases the count, and if
645+
the count is zero, it frees the resource.
646+
647+
As an example:
648+
649+
```{rust}
650+
fn foo () {
651+
let x = Arc::new(5i); // `x` has a count of 1.
652+
653+
{
654+
let y = x.clone(); // `x` has a count of 2.
655+
656+
{
657+
let z = x.clone() // `x` has a count of 3.
658+
} // `x` has a count of 2
659+
} // `x` has a count of 1
660+
} // `x` has a count of 0, and is destroyed
661+
```
662+
663+
The `Arc<T>` type doesn't handle circular references, though: if you have
664+
multiple `Arc<T>`s that refer to each other, their counts will always stay at
665+
one, even if nothing points to them, and you'll leak memory. In that case, the
666+
`Weak<T>` type can create a **weak pointer** to handle this case. If a group of
667+
references are all weak, then they can all be freed.
629668

630669
## Best practices
631670

632-
This part is coming soon.
671+
Use `Rc<T>` when you don't need thread safety, and `Arc<T>` when you do.
672+
673+
If you may introduce a reference cycle, consider adding a `Weak<T>` so that you
674+
don't leak memory.
633675

634676
# Gc
635677

0 commit comments

Comments
 (0)