Rust heap pointer types (Box, Rc/Arc, Weak) vs C++ shared_ptr and friends

Friends - Recently I had occasion to explore the new-ish C++11 library classes shared_ptr, unique_ptr, and weak_ptr. Rust's Rc/Arc, Box, and Weak struck me as very analogous (or the other way around if you wish), with one obvious difference being that C++ requires the programmer to know whether to use atomic operations on a shared_ptr (etc.) that is used across threads. I am wondering if anyone can either confirm this strong analogy or point out important differences (except lack of an explicit Rc vs. Arc distinction in C++)?

Also, where might RefCell, etc., fit into this analogy (if at all)?

Best - Eliot Moss

Rc doesn't exist in C++. Arc is the same as shared_ptr. Weak is the same as weak_ptr. Box is the same as unique_ptr.
RefCell doesn't exist in C++ since RefCell arises because of Rust's references, which have nothing to do with C++ references.
Apart from the obvious problems such as the absence of a dangling Box in safe Rust whilst a unique_ptr is fairly easy to dangle and/or double free, the semantic differences are probably absent.

7 Likes

The types that use interior mutability such as RefCell or Mutex and so on, generally correspond to two fields, one marked with the mutable keyword and storing the actual value, and some extra field used to control access to the value.

In the case of a RefCell, the extra field is a counter, and in the case of a Mutex, the extra field is a mutex. In the case of Cell, there's no extra field.

4 Likes

I think that's the main difference.

Rust's rules around mutability force you to synchronise access to the value behind an Arc if you want to mutate it, whereas you just need to "remember" in C++ (e.g. by storing a std::mutex as a field in your class and locking it in each method).

3 Likes

Thank you, folks - very helpful! EM

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.