Reference counted smart pointers

The ownership rule allows only one owner to exist at a time in a given scope. However, there are cases where you need to share the type with multiple variables. For instance, in a GUI library, each of the child widgets needs to have a reference to its parent container widget for things like communicating to layout the child widget based on resize events from the user. While lifetimes allow you to reference the parent node from the child nodes by storing the parent as a &'a Parent (say), it's often limited by the lifetime 'a of the value. Once the scope ends, your reference is invalid. In such cases, we need more flexible approaches, and that calls for using reference counting types. These smart pointer types provide shared ownership of values in the program.

Reference counting types enables garbage collection at a granular level. In this approach, a smart pointer type allows you to have multiple references to the wrapped value. Internally, the smart pointer keeps a count of how many references it has given out and are active using a reference counter (hereby refcount), which is just an integral value. As variables that reference the wrapped smart pointer value go out of scope, the refcount value decrements. Once all of the references to the object are gone and the refcount reaches 0, the value is deallocated. This is how reference counted pointers work in general.

Rust provides us with two kinds of reference counting pointer types:

  • Rc<T> : This is mainly for use in single threaded environments
  • Arc<T> is meant to be used in multi-threaded environments

Let's explore the single threaded variant here. We'll take a visit to its multi-threaded counterparts in Chapter 8, Concurrency.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset