Rc is a Reference-Counted Smart Pointer. While a Box object is
restricted to one owner only at a time, an Rc object can have
multiple owners. This is made possible because Rc keeps track of
the number of owners, and drops the object it points to only when
the count reaches zero. Rc provides static methods to create new
owners (through the clone() method) and get counts of the
references. See Table 1.
As an example, let us use an Rc object on an integer:
use std::rc::Rc;
let a = Rc::new(10);
Rc::strong_count(&a)Couldn't automatically determine type of variable `a`.
Please give it an explicit type.As we can see the number of references is 1, which is normal since
only the variable a owns this Rc.
Now let us define another owner:
let b = Rc::clone(&a);
Rc::strong_count(&a)The reference count is now 2.
We can check that both owners have access to the same value:
(*a, *b)Now if we drop a, the count decreases:
drop(a);
Rc::strong_count(&b)But the value is still accessible through b:
*bTable 1:Some methods of Rc
Method | Description |
|---|---|
| Constructs a new |
| Clones the |
| Returns a |
| Returns the current number of strong pointers to the |
| Returns the current number of weak pointers to the |