Friends - Recently I had occasion to explore the new-ish C++11 library classes
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
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
Weak is the same as
Box is the same as
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.
The types that use interior mutability such as
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.
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).
Thank you, folks - very helpful! EM