2 ms·
As someone who writes a lot of C++ and has played with Rust (ie, hello world) how does the language work when you remove shared pointers? Say I have an early-g
by zanny 13y ago
As someone who writes a lot of C++ and has played with Rust (ie, hello world) how does the language work when you remove shared pointers?
Say I have an early-generated state tracker for a whole bunch of events propagating in an event loop somewhere, that I want discarded when all the events finish. They are all separate tasks in different threads, so I either need to have some job that just checks if they all finish to clean up, or pass around shared data structures. How would you do that in Rust?
- banachtarski 13y agoI actually make it a point to do most of my code without shared_ptr, opting instead for unique_ptr. There was a talk somewhere about the "best written library you should never use" and shared_ptr was the focus. For the example you mentioned, you could have the parent object of those tasks responsible for cleanup of the shared object (e.g. each thread's destructor calls a finish function on the parent object). This is just one possible implementation. I don't encounter this as much because I prefer a shared-nothing approach where possible. edit:typo
- jmgrosen 13y agoIf the structure is immutable after you've produced it, you can use extra::arc::Arc<T> [0], and once all the references are dropped the memory will be deallocated. I haven't used C++, so this might be very similar to std::shared_ptr or not, but this is usually what one would use in Rust. (There's also extra::arc::RWArc<T> [1] when you need mutability, but that isn't used much in my experience.) [0] http://static.rust-lang.org/doc/master/extra/arc/struct.Arc.html http://static.rust-lang.org/doc/master/extra/arc/struct.Arc.... [1] http://static.rust-lang.org/doc/master/extra/arc/struct.RWArc.html http://static.rust-lang.org/doc/master/extra/arc/struct.RWAr...