FAQ - Help and questions

What replaces unique_ptr, shared_ptr and weak_ptr in Rust?

#porting#cpp#smart-pointerspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

unique_ptr becomes Box, and often disappears because a value is owned by its variable. shared_ptr becomes Rc on one thread and Arc across threads, and weak_ptr becomes Weak. Rc and Arc give shared read access only; to change shared data add RefCell or a Mutex. The compiler stops you using Rc across threads.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

C++ code often reaches for std::shared_ptr by habit, because ownership is hard to see. Port with the question "who owns this?" first. In Rust most values have one obvious owner, and the other users borrow with &T or &mut T, so a large part of the shared_ptr uses turn into plain values and references.

C++RustNotes
std::unique_ptr<T>Box<T> or just TBox for heap allocation, recursive types and trait objects
std::shared_ptr<T> (one thread)Rc<T>Counts owners; read-only access
std::shared_ptr<T> (several threads)Arc<T>Same with an atomic counter
std::weak_ptr<T>Weak<T>upgrade() gives Option<Rc<T>>
shared_ptr<T> with mutationRc<RefCell<T>>, Arc<Mutex<T>>The cell or lock is part of the type
raw T* that does not own&T, &mut TChecked by the compiler

The program shows each of them, with the counts printed. It was compiled and run with rustc 1.93.0.

src/main.rsrust
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::sync::Arc;

struct Owner {
    name: String,
    gadgets: RefCell<Vec<Weak<Gadget>>>,
}
struct Gadget {
    id: u32,
    owner: Rc<Owner>,
}

fn main() {
    // std::unique_ptr<T>  ->  Box<T>
    let b = Box::new(5);
    println!("{}", *b + 1);

    // std::shared_ptr<T>  ->  Rc<T> (one thread) or Arc<T> (shared between threads); counts are visible
    let a = Rc::new(String::from("shared"));
    let a2 = Rc::clone(&a);
    println!("rc strong = {}", Rc::strong_count(&a));
    drop(a2);
    println!("rc strong = {}", Rc::strong_count(&a));
    let arc = Arc::new(7);
    let t = { let arc = Arc::clone(&arc); std::thread::spawn(move || *arc * 2) };
    println!("arc: {} {}", t.join().unwrap(), Arc::strong_count(&arc));

    // std::weak_ptr<T>  ->  Weak<T>, used for the "back" link so that there is no cycle
    let owner = Rc::new(Owner { name: "Ada".into(), gadgets: RefCell::new(vec![]) });
    let g = Rc::new(Gadget { id: 1, owner: Rc::clone(&owner) });
    owner.gadgets.borrow_mut().push(Rc::downgrade(&g));
    println!("{} owns {} gadget(s); gadget {} belongs to {}", owner.name, owner.gadgets.borrow().len(), g.id, g.owner.name);
    println!("owner strong={} weak={}", Rc::strong_count(&owner), Rc::weak_count(&owner));
    drop(g);
    println!("after drop: upgrade -> {}", owner.gadgets.borrow()[0].upgrade().is_none());
}
text
6
rc strong = 2
rc strong = 1
arc: 14 1
Ada owns 1 gadget(s); gadget 1 belongs to Ada
owner strong=2 weak=0
after drop: upgrade -> true

Reading the output: cloning an Rc raises the strong count and dropping the clone lowers it; the Arc is back to 1 after the thread finished and dropped its clone. The owner's strong count is 2 because the variable owner and the gadget's owner field both hold it, while the owner keeps only a Weak pointer to the gadget. So when g, the gadget's last strong handle, is dropped, the gadget is freed, upgrade() on the weak pointer returns None (the last line prints true), and no cycle keeps anything alive.

How to do it#

  1. For each unique_ptr member, check if the member can simply be a value (T) or a Vec<T>. Use Box<T> only when you need an indirection: a recursive type, a very large value, or a trait object (Box<dyn Trait>).
  2. For each shared_ptr, find the real owner. If one exists, port to a reference or an id (see the thread on parent pointers and arenas). If sharing is real, use Rc (one thread) or Arc (several).
  3. If the shared data changes, add the cell or lock inside: Rc<RefCell<T>> checks borrows at run time and panics on a conflict; Arc<Mutex<T>> makes other threads wait.
  4. Keep back links Weak, as the code above does with gadgets.

Common mistakes#

  • Using Arc<Mutex<T>> everywhere "to be safe". It works, but it hides who owns what, and lock contention appears under load.
  • Using Rc in code that later moves to threads. The compiler error (Rc<..> cannot be sent between threads safely) is the fix prompt: switch to Arc.
  • Making reference cycles with Rc on both sides. They are never freed (see the thread on memory leaks).

Is Arc::clone expensive?#

It increments an atomic counter, which is cheap but not free, and costs more when many threads touch it. Clone it once per task, not once per item.

Where is make_shared?#

Rc::new and Arc::new.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet