Hacker News new | ask | show | jobs
by pimeys 1485 days ago
Isn't `weak_ptr` the same as `sync::Weak` in Rust? There are a few places I've seen this in use. One of them is if you want to build a tree of data you can traverse in any direction. E.g. parent -> child and from child -> parent again. One of the directions must hold a `sync::Weak`, otherwise we leak memory.

We've been going around this issue by storing flat collections instead of structuring the data as a tree. We for example have parents and children in adjacent vectors, and parent only needs to know the ids in the children vector to be able to iterate over them. In this case you can do a data structure storing the id values that are `Copy`, meaning this whole data structure can be `Copy` and is super easy to reason about.

The other use-case is a database connection pool. When you take a connection out from the pool, you get a reference to the pool itself. The pool is quite often internally inside an `Arc`, and the connection gets wrapped into a guard object holding a `Weak` to the pool. With RAII when the connection drops out from the scope, the `Weak` is checked is it still valid (is the pool alive) and if so, the connection is returned back to the pool.