0:00
/
0:00
Transcript

Code on GitHub: https://github.com/caveofprogramming/rust/

The Cave of Programming Blog is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.

Consider a tree structure, where every node in the tree may have child nodes.

A node may appear multiple times at different points in the tree.

How do we ensure that every node is cleaned up (dropped) eventually, but is never dropped as long as at least one other node still refers to it?

This can be accomplished using reference counting.

Example Struct

I will use the following struct, representing person data. I’ve implemented the Drop trait so that we can see exactly when a Person object is dropped.

Managing the Object

We can use std::rc::Rc to initially own the object.

The object then has a reference count of 1.

After this we can create more variables that own the object, incrementing the reference count.

The object will only be cleaned up and drop() called when all of these references have been dropped or have gone out of scope.

We can drop these references manually if desired, in any order.

The Rc object keeps a count of how many references still refer to the object, and the object gets dropped when there are none left.

The Cave of Programming Blog is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.

Discussion about this video