Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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:

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:

The reference count is now 2.

We can check that both owners have access to the same value:

Now if we drop a, the count decreases:

But the value is still accessible through b:

Table 1:Some methods of Rc

Method

Description

new(x)

Constructs a new Rc object.

clone(&rc)

Clones the Rc object, increasing the strong reference count.

downgrade(&rc)

Returns a Weak pointer to the contained object and increases the weak reference count.

strong_count(&rc)

Returns the current number of strong pointers to the Rc object.

weak_count(&rc)

Returns the current number of weak pointers to the Rc object.

see solution