问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/53962054/how-does-rust-handle-the-island-of-isolation-cycles-of-references-scenario-f