Rc

Now, let's consider one last single-item container before we get into a multi-item container. We'll look into Rc<T>, described by the Rust documentation as being a single-threaded reference-counting pointer. Reference counting pointers are distinct from the usual Rust references in that, while they are allocated on the heap as a Box<T>, cloning a reference counter pointer does not cause a new heap allocation, bitwise copy. Instead, a counter inside the Rc<T> is incremented, somewhat analogously as to the way RefCell<T> works. The drop of an Rc<T> reduces that internal counter and when the counter's value is equal to zero, the heap allocation is released. Let's take a peek inside src/liballoc/rc.s:

pub struct Rc<T: ?Sized> { ptr: Shared<RcBox<T>>, ...

Get Hands-On Concurrency with Rust now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.