How does Rust handle the "island of isolation" scenario for Rc
s and Arc
s?
An "island of isolation" is a situation where object A
contains a pointer to object B
and object B
contains a pointer to object A
, but there are no pointers to either objects anywhere else.
Is Rust smart enough to detect this or does it lead to memory leaks?
To enable multiple ownership, Rust has a type called Rc<T> . Its name is an abbreviation for reference counting, which keeps track of the number of references to a value to know whether or not a value is still in use.
Reference counting in naive form has two main disadvantages over the tracing garbage collection, both of which require additional mechanisms to ameliorate: The frequent updates it involves are a source of inefficiency.
Rust does not have a garbage collector, and it won't detect reference cycles. If your program creates inaccessible reference cycles, they are leaked, and it is up to you to avoid them, e.g. by using weak references, or by not using shared ownership in the first place.
Note that the only way to create a reference cycle is to use both shared ownership and interior mutability.
See also the chapter on reference cycles in the Rust book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With