Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust handle the "island of isolation" (cycles of references) scenario for reference-counted types?

How does Rust handle the "island of isolation" scenario for Rcs and Arcs?

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?

like image 353
Ayman Madkour Avatar asked Dec 28 '18 17:12

Ayman Madkour


People also ask

Does rust use reference counting?

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.

What is one of the typical disadvantages of implementing garbage collection using reference counters?

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.


1 Answers

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.

like image 154
Sven Marnach Avatar answered Sep 23 '22 13:09

Sven Marnach