skip to content

In Rust, what does `Rc::clone(&config)` do to an `Rc<String>`, and when is the `String` itself dropped?

level: juniorimportance: must knowfreq 74%

answer

  1. a new handle, not a new String
  2. strong count goes up by one
  3. each dropped handle counts down
  4. zero strong handles: value dropped

basics

~20 s

Rc::clone copies no String data: it adds one to the strong count and returns another pointer to the same heap allocation. Each Rc dropped subtracts one, and the String is dropped when the last strong Rc goes away.

solid answer

~40 s

`Rc::new` moves the `String` into one heap allocation that also holds a strong count and a weak count. `Rc::clone(&config)` adds one to the strong count and hands back another pointer to that same allocation, so it is cheap however large the `String` is; `config.clone()` is the same call, but the std docs call `Rc::clone(&config)` the more idiomatic spelling because it signals a cheap handle copy. Dropping any handle subtracts one, and when the strong count reaches zero the `String` is dropped, even if `Weak` handles remain. Copying the text itself takes `(*config).clone()`. The handles only give out `&String`: assigning through one fails with E0594 (cannot assign to data in an `Rc`).

code

rust · 18 lines
rust
use std::rc::Rc;

fn main() {
    let config = Rc::new(String::from("theme=dark"));
    println!("after new: strong = {}", Rc::strong_count(&config));

    let for_header = Rc::clone(&config); // bumps the count, no String copy
    let for_footer = config.clone();     // same call, method syntax
    println!("after two clones: strong = {}", Rc::strong_count(&config));
    println!("same allocation: {}", Rc::ptr_eq(&config, &for_header));
    println!("same heap buffer: {}", config.as_ptr() == for_footer.as_ptr());

    drop(for_header);
    println!("after one drop: strong = {}", Rc::strong_count(&config));

    let deep: String = (*config).clone(); // this one copies the String
    println!("deep copy shares buffer: {}", deep.as_ptr() == config.as_ptr());
}

go deeper

for a junior

Recall that Rc::clone only bumps a strong count and shares one allocation, and that the inner value drops when the last Rc handle is dropped.

for a middle

Explain the two counts in the allocation, why the value drops at strong zero while the allocation waits for weak zero, and why assignment through an Rc fails with E0594.

for a senior

Show you watch for hidden deep copies, such as (*rc).clone() or a T::clone in a loop, and that you know whoever drops the last handle runs the destructor at that point.

for a principal

Frame Rc as a choice of shared ownership on one thread and argue when a single owner with borrows, or an index into a collection, keeps the destructor's timing easier to reason about.

## What `Rc<T>` is `std::rc::Rc<T>` is Rust's **single-threaded reference-counted pointer**. It exists for the case where one value has several owners and none of them can be picked as the one that frees it: a configuration shared by several widgets, a node reachable from two places in a graph, an asset used by many sprites in a game. `Rc::new(value)` moves `value` into a **heap allocation** that holds three things: - the **strong count**, the number of live `Rc` handles; - the **weak count**, which tracks the live `Weak` handles; - the **inner value** itself. In the standard library source the two counts are plain `Cell<usize>` fields of a private `RcInner<T>` struct. Every `Rc` handle is one pointer to that allocation. ## What `Rc::clone` does, and does not do `Rc<T>` implements `Clone` for every `T`, including types that are not `Clone` themselves. Its `clone`: 1. adds one to the strong count; 2. returns a new `Rc<T>` holding the same pointer. Nothing in the inner value is touched. Cloning an `Rc<String>` that holds a megabyte of text costs the same as cloning an `Rc<u8>`. The std docs say the two spellings below are equivalent, and call the first the most idiomatic because it makes clear the code creates a new reference rather than copying the whole content: | Expression | Calls | Copies the `String` bytes? | Result type | |---|---|---|---| | `Rc::clone(&config)` | `Clone for Rc` | no | `Rc<String>` | | `config.clone()` | `Clone for Rc` (method lookup finds `Rc` first) | no | `Rc<String>` | | `(*config).clone()` | `Clone for String` | **yes** | `String` | | `Rc::downgrade(&config)` | `Rc::downgrade`, adds one to the weak count | no | `Weak<String>` | Because `Rc` dereferences to `T` through `Deref`, you can call `String` methods straight on the handle, which is also why `Rc`'s own functions (`Rc::strong_count`, `Rc::downgrade`, `Rc::ptr_eq`) are associated functions called with the type name: they must not clash with a method of the same name on `T`. ## When the value and the memory go away Each time an `Rc` handle is dropped, at the end of its scope, through `drop(handle)`, or when the struct holding it is dropped, the strong count falls by one. The `Drop` impl's own doc spells out the rule: when the strong count reaches zero, the only other references (if any) are `Weak`, so the inner value is dropped. There are two separate moments: - **Inner value dropped**: when the **strong** count hits zero. The `String`'s destructor runs and its text buffer is freed. - **Allocation freed**: when the **weak** count also hits zero. A lingering `Weak` keeps the small block holding the two counts and the (already dropped) value's slot alive, but never the value. This is ordinary `Drop`, run deterministically at a known point, not a background collector. Rust's guarantee is narrower than "everything is always freed": a cycle of `Rc` handles never reaches zero, which is the subject of `Weak`. ## What the handles let you do `Rc` gives out only shared access. `Deref` yields `&T`, and `Rc` does not implement `DerefMut`, so `*config = String::new()` or `*counter += 1` on an `Rc<i32>` is rejected with **E0594** (cannot assign to data in an `Rc`). Mutating shared data needs either interior mutability inside the `Rc` (covered with Cell and RefCell) or one of `Rc`'s uniqueness-checked functions, `Rc::get_mut` and `Rc::make_mut`. Two more facts that come up in a first interview: - `Rc::strong_count(&rc)` and `Rc::weak_count(&rc)` read the counts; they are useful in tests and debugging, not as program logic. - `Rc::ptr_eq(&a, &b)` tells you whether two handles point at the **same allocation**, which `==` does not: `==` on two `Rc<String>` compares the strings. ## In practice - Reach for `Rc` when ownership is genuinely shared on one thread; a single owner wants `Box<T>` or a plain value, and a short-lived shared view wants `&T`. - Prefer `Rc::clone(&x)` so a reviewer never mistakes a handle copy for a deep copy. - Treat the strong count as the lifetime of the value: whoever drops the last `Rc` runs the destructor, wherever that happens to be. ## Mistakes interviewers listen for - Saying `rc.clone()` copies the data. It does not, unless you dereference first. - Expecting the value to die when the variable that called `Rc::new` goes out of scope. A clone stored in a struct or returned from a function keeps it alive. - Assuming a `Weak` handle keeps the value alive. It counts toward the weak count only, which never delays the destructor. - Reaching for `Rc` to share across threads. Its counts are not atomic, so it is neither `Send` nor `Sync`; the threads material covers the atomic alternative.

  • If `Rc<T>` is `Clone` for any `T`, can you put a type that is not `Clone` behind an `Rc` and share it?
    Yes. `Clone for Rc<T>` has no `T: Clone` bound, because it only bumps the strong count and copies a pointer. A `struct Texture` that owns a GPU handle and deliberately is not `Clone` can be shared through `Rc<Texture>`. What you lose is `Rc::make_mut` and `Rc::unwrap_or_clone`, which need to clone `T` when the handle is not unique.
  • Why are `strong_count` and `downgrade` called as `Rc::strong_count(&rc)` rather than `rc.strong_count()`?
    `Rc<T>` dereferences to `T`, so method syntax would search `T`'s methods too. If `T` had its own `strong_count` or `downgrade`, the two would clash. Making `Rc`'s operations associated functions keeps `rc.method()` meaning `T`'s method unambiguously, and the std docs say this is the reason.
  • What does `==` compare between two `Rc<String>` handles?
    The strings. `PartialEq for Rc<T>` compares the inner values, so two separate allocations holding equal text are `==`. To ask whether two handles share one allocation, use `Rc::ptr_eq(&a, &b)`.

A shared meeting room with a tally on the door: each person who comes in adds a mark (Rc::clone), each one who leaves rubs one out (drop), and whoever leaves last switches off the lights. Nobody gets a copy of the room.

  • Rc::clone deep-copies the inner value like any other clone call.
  • The value is freed when the variable passed to Rc::new goes out of scope.
  • A live Weak handle keeps the inner value from being dropped.
  • You can assign through an Rc as long as the binding is declared mut.
  • Rc frees shared data with a background garbage collector.