Course contentsShow
← Rust
Lesson 1000 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

The Lifecycle of an Rc Instance

Manage the creation, cloning, and dropping of reference-counted pointers.

In this lesson, you will learn how the Rc<T> smart pointer tracks references to shared heap data to determine exactly when memory can be safely deallocated.

The Shared Ownership Model

Unlike Box<T>, which enforces strict single ownership, Rc<T> (Reference Counted) allows multiple parts of your program to own the same data on the heap. Because Rust must ensure memory is cleaned up only when the last owner is finished, Rc<T> maintains a hidden counter—the "reference count"—somewhere on the heap alongside your data.

Creation and Cloning

When you initialize an Rc<T>, you are placing a value on the heap and wrapping it in a structure that tracks the count.

use std::rc::Rc;

let data = Rc::new(String::from("Shared Data"));
// Count is 1

When you call data.clone(), you aren't copying the String itself. Instead, you are creating a new Rc instance that points to the same heap location and incrementing the reference count by 1.

let other_reference = data.clone();
// Count is 2

The Drop Lifecycle

The lifecycle of the data is tied to the lifecycle of these Rc instances. When an Rc variable goes out of scope, its Drop implementation is triggered. Instead of immediately freeing the heap memory, the Rc pointer performs two steps:

  1. It decrements the reference count.
  2. It checks: "Is the count now zero?"

If the count is greater than zero, the heap memory remains untouched. If the count reaches zero, it signifies that no more owners exist, and the Rc structure automatically deallocates the heap memory.

This mechanism allows you to share data across different scopes without needing to track lifetimes manually, provided you remain in a single-threaded context. If you tried to share this across threads, the compiler would stop you, as the reference counting mechanism in Rc is not atomic and thus not thread-safe.

Key Takeaway: An Rc instance keeps its heap-allocated data alive as long as the reference count remains above zero; once the last Rc clone is dropped, the memory is automatically reclaimed.