# Rc vs Arc in Rust: Memory Layout, Send/Sync Bounds, and Atomic Orderings

> How Rc<T> and Arc<T> actually work in Rust's standard library: single-allocation layout, conditional Send/Sync bounds, Relaxed/Release/Acquire reference counting, mutation patterns, and cycle leaks.

- URL: https://zeljic.com/blog/rc-vs-arc-in-rust/
- Author: Đorđe Zeljić
- Published: 2026-12-01
- Tags: rust, concurrency, borrowing, memory-safety, performance

`std::rc::Rc<T>` and `std::sync::Arc<T>` both give a heap-allocated `T` multiple owners via reference counting, and both hand out only shared references (`&T`) on dereference. Summarizing them as "`Rc` for single-threaded code, `Arc` for multithreaded code" is a useful starting rule, but it skips four details that matter in real Rust code: how the heap allocation is laid out, when `Arc<T>` actually implements `Send` and `Sync`, what atomic memory orderings `Arc` pays for, and how mutation and reference cycles behave.

## One Allocation, Two Counters

Unlike `std::shared_ptr<T>(new T)` in C++, `Rc::new` and `Arc::new` never allocate a separate control block. Both place the strong count, the weak count, and the payload `T` contiguously in a single heap allocation (`alloc/src/rc.rs` and `alloc/src/sync.rs`):

```rust
// Simplified from alloc/src/rc.rs and alloc/src/sync.rs
#[repr(C, align(2))]
struct RcInner<T: ?Sized> {
    strong: Cell<usize>,
    weak: Cell<usize>,
    value: T,
}

#[repr(C, align(2))]
struct ArcInner<T: ?Sized> {
    strong: AtomicUsize,
    weak: AtomicUsize,
    data: T,
}
```

On the stack, both `Rc<T>` and `Arc<T>` are a single `NonNull` pointer for `T: Sized` (one machine word), or a two-word fat pointer for dynamically sized types such as `Arc<str>` and `Arc<[u8]>`.

Both constructors initialize `strong = 1` and `weak = 1`. That initial `weak = 1` is an implicit weak lease collectively held by all strong owners. Splitting teardown across the two counters gives two distinct lifetimes:

1. When the last `Rc<T>` or `Arc<T>` is dropped (`strong` reaches `0`), `T`'s destructor runs immediately in place (`ptr::drop_in_place`), and that implicit weak lease is released.
2. The `RcInner<T>` / `ArcInner<T>` heap block itself is only deallocated when `weak` reaches `0`.

```rust
use std::mem::size_of;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};

fn main() {
    assert_eq!(size_of::<Rc<String>>(), size_of::<usize>());
    assert_eq!(size_of::<Arc<String>>(), size_of::<usize>());
    assert_eq!(size_of::<Arc<str>>(), 2 * size_of::<usize>());

    static DROPS: AtomicUsize = AtomicUsize::new(0);
    struct Tracked(&'static str);
    impl Drop for Tracked {
        fn drop(&mut self) {
            DROPS.fetch_add(1, Ordering::Relaxed);
        }
    }

    let a = Arc::new(Tracked("payload"));
    let b = Arc::clone(&a);
    let weak: Weak<Tracked> = Arc::downgrade(&a);

    assert_eq!(a.0, "payload");
    assert!(Arc::ptr_eq(&a, &b));
    assert_eq!(Arc::strong_count(&a), 2);
    assert_eq!(Arc::weak_count(&a), 1); // excludes the implicit strong lease

    drop(a);
    assert_eq!(DROPS.load(Ordering::Relaxed), 0);
    assert!(weak.upgrade().is_some());

    drop(b);
    // `Tracked::drop` has already run, even though `weak` still keeps
    // the `ArcInner<Tracked>` allocation alive until `weak` is dropped.
    assert_eq!(DROPS.load(Ordering::Relaxed), 1);
    assert!(weak.upgrade().is_none());
}
```

That split matters when `T` is large inline: a lingering `Weak<[u8; 1_048_576]>` keeps the full 1 MiB `ArcInner` block allocated after the last `Arc` drops, whereas a lingering `Weak<Vec<u8>>` only retains the three-word `Vec` header plus the two counters because `Vec::drop` already freed its heap buffer.

## `Send` and `Sync`: Unconditional vs Conditional

`Rc<T>` opts out of both marker traits unconditionally:

```rust
impl<T: ?Sized, A: Allocator> !Send for Rc<T, A> {}
impl<T: ?Sized, A: Allocator> !Sync for Rc<T, A> {}
```

You can move an `Rc<T>` freely within a single thread, or hold it across `.await` points inside a `!Send` future on a single-threaded executor (`tokio::task::LocalSet`). What fails at compile time is crossing a `Send` boundary such as `std::thread::spawn` (`F: FnOnce() -> T + Send + 'static`) or `tokio::spawn`:

```rust
use std::rc::Rc;
use std::thread;

fn main() {
    let rc = Rc::new(42);
    thread::spawn(move || {
        println!("{rc}");
    });
}
```

```text
error[E0277]: `Rc<i32>` cannot be sent between threads safely
  --> src/main.rs:6:19
   |
6  |     thread::spawn(move || {
   |     ------------- ^------
   |     |             |
   |     |             within this `{closure@...}`
   |     required by a bound introduced by this call
   = help: within `{closure@...}`, the trait `Send` is not implemented for `Rc<i32>`
```

`Arc<T>`, on the other hand, is **not** unconditionally thread-safe. In `alloc/src/sync.rs`, both `Send` and `Sync` on `Arc<T>` require `T: Send + Sync`:

```rust
unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Send> Send for Arc<T, A> {}
unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Sync> Sync for Arc<T, A> {}
```

Both bounds are necessary:

- **Why `Arc<T>: Send` requires `T: Sync`:** cloning an `Arc<T>` and sending the clone to another thread gives two threads `&T` at the same time—the exact definition of `T: Sync`.
- **Why `Arc<T>: Sync` (and `Send`) requires `T: Send`:** whichever thread drops the last `Arc<T>` runs `T::drop` on that thread (or takes ownership via `Arc::into_inner`), transferring destruction of `T` across threads.

Wrapping a single-threaded interior-mutability type like `Cell<T>` or `RefCell<T>` in `Arc` compiles locally, and then fails the moment it touches a thread boundary:

```rust
use std::cell::Cell;
use std::sync::Arc;
use std::thread;

fn main() {
    let shared = Arc::new(Cell::new(0));
    let c = Arc::clone(&shared);
    thread::spawn(move || {
        c.set(1);
    });
}
```

```text
error[E0277]: `Cell<i32>` cannot be shared between threads safely
  = help: the trait `Sync` is not implemented for `Cell<i32>`
  = note: if you want to do aliasing and mutation between multiple threads,
          use `std::sync::RwLock` or `std::sync::atomic::AtomicI32` instead
  = note: required for `Arc<Cell<i32>>` to implement `Send`
```

By contrast, `Mutex<T>` implements both `Send` and `Sync` whenever `T: Send`, so `Arc<Mutex<Vec<u8>>>` satisfies `Send + Sync`:

```rust
use std::sync::{Arc, Mutex};

fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}

fn main() {
    assert_send::<Arc<i32>>();
    assert_sync::<Arc<i32>>();

    assert_send::<Arc<Mutex<Vec<u8>>>>();
    assert_sync::<Arc<Mutex<Vec<u8>>>>();
}
```

## What `Arc` Actually Pays For: Atomic Orderings and Codegen

A common misconception is that every `Arc::clone` emits a full memory barrier (`SeqCst`) to synchronize CPU cores. There is **no `SeqCst`** anywhere in `Arc`'s reference-counting logic (`alloc/src/sync.rs`):

- **`Arc::clone`** increments `strong` with `fetch_add(1, Ordering::Relaxed)` (and aborts if the count exceeds `isize::MAX as usize`, preventing a `mem::forget` loop from wrapping `strong` to `0` and causing use-after-free). `Relaxed` needs no happens-before synchronization because a new `Arc` can only be created from an existing live `Arc`, and passing that reference to another thread already had to synchronize.
- **`Arc::drop`** decrements `strong` with `fetch_sub(1, Ordering::Release)`. If the previous count was not `1`, `drop` returns immediately. **Only when the previous count was `1`** does the last owner execute `atomic::fence(Ordering::Acquire)` before calling `drop_slow()`. That `Release`/`Acquire` pair guarantees that every read or interior write on earlier threads (for instance through a `Mutex<T>`, which is not locked when dropped) happens-before `T::drop` runs on the final thread. This exact `Relaxed`-clone / `Release`-drop / `Acquire`-fence protocol has been mechanically verified against the C20 memory model ([Jacobs & Fasse, 2025](https://arxiv.org/abs/2505.00449)).
- **`Weak::upgrade`** uses a `compare_exchange_weak` loop (`Acquire` on success, `Relaxed` on failure) so it never increments a strong counter that has already reached `0`.

Why is `Arc` still slower than `Rc`? Two separate reasons show up at different scales:

1. **Optimizer freedom on a single thread.** Because `Rc`'s counter is a plain `Cell<usize>`, LLVM can merge or completely eliminate redundant clone/drop pairs. It cannot elide atomic read-modify-write instructions. Compare `rustc -O` output on `x86_64` for cloning and immediately dropping in the same scope:

```rust
use std::rc::Rc;
use std::sync::Arc;

pub fn read_rc(x: &Rc<u64>) -> u64 {
    let c = Rc::clone(x);
    *c
}

pub fn read_arc(x: &Arc<u64>) -> u64 {
    let c = Arc::clone(x);
    *c
}
```

```asm
; read_rc: LLVM elides both the increment and the decrement
read_rc:
    mov rax, qword ptr [rdi]
    cmp qword ptr [rax], -1
    je  .Labort
    mov rax, qword ptr [rax + 16] ; offset +16 skips `strong` and `weak`
    ret

; read_arc: atomic RMWs (`lock inc` / `lock dec`) cannot be elided
read_arc:
    mov  rax, qword ptr [rdi]
    lock inc qword ptr [rax]
    ...
    mov  rbx, qword ptr [rax + 16]
    lock dec qword ptr [rax]
    jne  .Ldone
    ; Acquire fence + cold call to drop_slow
```

2. **Cache-line contention across cores.** Uncontended `lock inc` / `lock dec` on a cache line owned exclusively in L1 costs only a few nanoseconds. When many worker threads clone and drop the *same* `Arc` in a hot loop, cores repeatedly invalidate each other's cache line for `ArcInner`. Borrow `&T` inside functions and only call `Arc::clone` when crossing a thread or task boundary:

```rust
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;

fn inspect_ports(ports: &[u16]) -> usize {
    ports.len()
}

fn main() {
    let config: Arc<[u16]> = Arc::from([8080, 8081, 8082]);
    let hits = Arc::new(AtomicUsize::new(0));

    thread::scope(|s| {
        for _ in 0..4 {
            // Clone once per thread boundary, then pass `&[u16]` inside the worker.
            let cfg = Arc::clone(&config);
            let hits = Arc::clone(&hits);
            s.spawn(move || {
                assert_eq!(inspect_ports(&cfg), 3);
                hits.fetch_add(1, Ordering::Relaxed);
            });
        }
    });

    assert_eq!(hits.load(Ordering::Relaxed), 4);
}
```

## Mutating Through `Rc<T>` and `Arc<T>`

Neither `Rc<T>` nor `Arc<T>` implements `DerefMut`, because multiple owners could otherwise obtain aliasing `&mut T` references. Depending on whether ownership is currently unique, mostly read-only, or concurrently mutated, the standard library gives you three patterns (`Rc` exposes the single-threaded equivalents):

```rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    // 1. Unique-owner mutation: `Arc::get_mut`
    // Succeeds iff `strong_count == 1` AND `weak_count == 0` (no other `Arc` or `Weak` exists).
    let mut data = Arc::new(vec![1, 2, 3]);
    Arc::get_mut(&mut data).unwrap().push(4);
    assert_eq!(*data, [1, 2, 3, 4]);

    let observer = Arc::downgrade(&data);
    // Even one live `Weak` makes `get_mut` return `None`, because another
    // thread could call `observer.upgrade()` concurrently.
    assert!(Arc::get_mut(&mut data).is_none());
    drop(observer);
    assert!(Arc::get_mut(&mut data).is_some());

    // 2. Clone-on-write: `Arc::make_mut` (requires `T: Clone`)
    // Clones `T` into a new `Arc` when shared; mutates in place when unique.
    let snapshot = Arc::clone(&data);
    Arc::make_mut(&mut data).push(5); // `snapshot` is untouched
    assert_eq!(*snapshot, [1, 2, 3, 4]);
    assert_eq!(*data, [1, 2, 3, 4, 5]);

    let ptr_before = Arc::as_ptr(&data);
    Arc::make_mut(&mut data).push(6); // unique again -> zero-copy in-place mutation
    assert_eq!(ptr_before, Arc::as_ptr(&data));

    // If `strong == 1` but `Weak` pointers exist, `make_mut` moves `T` into a
    // fresh `Arc` without calling `T::clone()` and invalidates old `Weak` pointers:
    let stale_weak = Arc::downgrade(&data);
    Arc::make_mut(&mut data).push(7);
    assert!(stale_weak.upgrade().is_none());

    // 3. Concurrent shared mutation: `Arc<Mutex<T>>` / `Arc<RwLock<T>>` / atomics
    let counter = Arc::new(Mutex::new(0usize));
    let handles: Vec<_> = (0..4)
        .map(|_| {
            let counter = Arc::clone(&counter);
            thread::spawn(move || {
                *counter.lock().unwrap() += 1;
            })
        })
        .collect();

    for h in handles {
        h.join().unwrap();
    }
    assert_eq!(*counter.lock().unwrap(), 4);
}
```

On read-heavy paths—such as routing tables or feature flags—publishing a new immutable `Arc<Config>` snapshot (or using `Arc::make_mut` on the writer and swapping the pointer) avoids `Mutex` contention on readers altogether. When state is mutated continuously, owning `T` inside a single task and sending commands over an `mpsc` channel often beats scattering `Arc<Mutex<T>>` across callers.

## Reference Cycles and `Weak<T>`

Preventing memory leaks is intentionally outside Rust's safety guarantees (`std::mem::forget` and `Box::leak` are safe functions). If two `Rc` or `Arc` allocations hold strong references to each other through interior mutability, neither strong count ever reaches `0`, and neither `Drop` implementation ever runs:

```rust
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};

fn main() {
    // 1. A cycle of strong `Rc` pointers leaks deterministically:
    let leak_drops = Rc::new(Cell::new(0usize));

    struct LeakyNode {
        next: RefCell<Option<Rc<LeakyNode>>>,
        drops: Rc<Cell<usize>>,
    }
    impl Drop for LeakyNode {
        fn drop(&mut self) {
            self.drops.set(self.drops.get() + 1);
        }
    }

    {
        let a = Rc::new(LeakyNode {
            next: RefCell::new(None),
            drops: Rc::clone(&leak_drops),
        });
        let b = Rc::new(LeakyNode {
            next: RefCell::new(Some(Rc::clone(&a))),
            drops: Rc::clone(&leak_drops),
        });
        *a.next.borrow_mut() = Some(Rc::clone(&b));
        assert_eq!(Rc::strong_count(&a), 2);
        assert_eq!(Rc::strong_count(&b), 2);
    }
    // Both `a` and `b` went out of scope, dropping strong counts from 2 to 1:
    assert_eq!(leak_drops.get(), 0);

    // 2. Break cycles with `Weak<T>` along non-owning edges (e.g. child -> parent).
    // `Arc::new_cyclic` (and `Rc::new_cyclic`) wires the `Weak` back-pointer
    // during construction without needing a `Mutex` or `RefCell`:
    let clean_drops = Arc::new(AtomicUsize::new(0));

    struct Parent {
        children: Vec<Arc<Child>>,
        drops: Arc<AtomicUsize>,
    }
    struct Child {
        id: u32,
        parent: Weak<Parent>,
        drops: Arc<AtomicUsize>,
    }
    impl Drop for Parent {
        fn drop(&mut self) {
            self.drops.fetch_add(1, Ordering::Relaxed);
        }
    }
    impl Drop for Child {
        fn drop(&mut self) {
            self.drops.fetch_add(1, Ordering::Relaxed);
        }
    }

    {
        let parent = Arc::new_cyclic(|weak_parent| {
            // `strong` is 0 while `Parent` is being constructed:
            assert!(weak_parent.upgrade().is_none());

            Parent {
                children: vec![
                    Arc::new(Child {
                        id: 1,
                        parent: weak_parent.clone(),
                        drops: Arc::clone(&clean_drops),
                    }),
                    Arc::new(Child {
                        id: 2,
                        parent: weak_parent.clone(),
                        drops: Arc::clone(&clean_drops),
                    }),
                ],
                drops: Arc::clone(&clean_drops),
            }
        });

        assert_eq!(parent.children[0].id, 1);
        assert!(parent.children[0].parent.upgrade().is_some());
        assert_eq!(Arc::strong_count(&parent), 1);
        assert_eq!(Arc::weak_count(&parent), 2);
    }

    assert_eq!(clean_drops.load(Ordering::Relaxed), 3);
}
```

Note that inside the `new_cyclic` closure, calling `weak_parent.upgrade()` returns `None` until the closure finishes initializing `Parent` and `strong` transitions from `0` to `1`.

## Summary

| Property | `Rc<T>` | `Arc<T>` |
| --- | --- | --- |
| Heap layout | Single allocation: `Cell<usize>` strong + weak + `T` | Single allocation: `AtomicUsize` strong + weak + `T` |
| `Send` / `Sync` | Never (`!Send`, `!Sync`) | Only when `T: Send + Sync` |
| `clone` / `drop` cost | Non-atomic load/store; clone+drop pairs can be elided by LLVM | `Relaxed` `fetch_add` on clone; `Release` `fetch_sub` on drop + `Acquire` fence on final drop; never elided |
| Mutation options | `Rc::get_mut`, `Rc::make_mut`, `Cell<T>` / `RefCell<T>` | `Arc::get_mut`, `Arc::make_mut`, `Mutex<T>` / `RwLock<T>` / atomics |
| Cycle behavior | Leaks unless non-owning edges use `rc::Weak<T>` | Leaks unless non-owning edges use `sync::Weak<T>` |

Reach for `&T` first when lifetimes fit a lexical scope, `Rc<T>` when shared ownership stays on one thread, and `Arc<T>` when ownership genuinely crosses thread or `Send` task boundaries—cloning at the boundary and borrowing `&T` everywhere inside.
