4 ms·
One issue with languages that use smart pointers (as opposed to a global garbage collector) for memory management is circular references. For example, one can c
by thebear 14y ago
One issue with languages that use smart pointers (as opposed to a global garbage collector) for memory management is circular references. For example, one can create a memory leak with C++ shared pointers by having two objects each of which holds a shared pointer to the other. In C++, the solution is to use a weak pointer for one of the two pointers. This raises two questions: 1) Since the Rust compiler is more vigilant than the C++ compiler, does it do anything to prevent "pointer circles?" 2) Am I correct in assuming that the solution in Rust is to use a reference for one of the owning pointers? In other words, is the Rust reference the analogue to the C++ weak pointer?
- pcwalton 14y agoYou can use Rust references that way to some extent, although the safety check for references will probably prevent you from using it to do what you want in all cases. In general, you need to follow a stack discipline with your references. For example, you can't make a doubly linked list using unique smart pointers and references as the backpointers; the Rust compiler will be unable to prove it safe. (In general, while placing references inside data structures can be done, it requires some knowledge of the how the safety check works—this is where the "lifetime parameters" come in.) The good news is that the Rust compiler does detect and clean up cycles of `@` smart pointers. At the moment, this is done at thread death only. But Graydon is nearly done with a new tracing garbage collector (written in Rust) that correctly detects and cleans up cycles.
- thebear 14y agoThanks for the explanation, this really piques my interest in Rust. BTW, now I have a follow-up to my question whether Rust's references are the analogue to C++ weak pointers. C++ weak pointers can be dangling, but in a controlled manner, that is, one can ask them whether they're dangling or not. Am I correct in assuming that Rust will never allow anything like a dangling pointer, not even the "controlled dangling" of a C++ weak pointer?
- pcwalton 14y agoRight, Rust references are never dangling. But there might end up being true weak references in the standard library, which would be more like a C++ weak pointer. (I'd take a patch for them if anyone needed them, though it's blocked on the GC landing.)