Hacker News new | ask | show | jobs
by pjmlp 4129 days ago
I don't get why they just don't suggest using weak_ptr<>() for the backwards reference.
3 comments

You need to use weak pointers for backpointers in Rust, because there's no GC. If you create a cycle with reference counted objects, objects are never released and the program will leak memory.
Of course, but my question was why it wasn't explained, I know very well the reason why weak pointers are required.
There's little benefit to doing so. Because weak_ptr points to a shared_ptr, you are still paying the overhead of the reference counting either way. You might as well just use shared_ptr and have a destructor that unlinks every element from the list.

weak_ptr is basically for managing leaks, not for avoiding reference count overhead. Leaks aren't the problem in a doubly-linked list, however.

Thanks for jumping in. Yeah I guess it makes sense.

It just got me thinking into having some kind of data structure examples in Rust as side project, after 1.0 availability.

Now just have to find time for it.

I guess this would solve the problem but it would also be slow because traversing the list via weak_ptr requires a conversion from weak_ptr to shared_ptr for every item.
There isn't any choice in RC systems in presence of cycles, either weak pointers or a presence of cycle collector.

Anything else is unsafe, specially if the pointer is allowed to escape the RC object that contains it.

And this is one of the reasons why usually optimized GCs outperform RC solutions.

Unless approaches like affine types or counting elision are used, but those fail down in the presence of cycles, forcing the developers to use other approaches to represent cycles.