In most cases, ownership is clear.
We know exactly which variable owns what value, but sometimes there are cases where a single value
might have or need multiple owners.
For example, the graph data struck.
If we look in here, we see that we have multiple nodes of zero, one, two, three and four, and then
each of these nodes has an edge pointing to it.
Well, Node zero is connected to Node one and four.
So we can say logically that.
No zero had multiple owners of one and four.
So for us to allow multiple ownership, we have RC, which stands for reference counted.
RC is also allocated on the heap and RC is going to track the number of references to evaluate whether
or not a value is still in use.
Naturally, if there are zero references, then the value is cleaned up.
As a side note, there is also Ark RC, which stands for Atomic Reference Counting.
It is the same thing as RC, but ARC is designed for safe sharing between threads, so only use arc
when sharing the pointer between threads.
Otherwise stick to RC.
Now let's see an example of RC.
So the first thing we need to do is actually bring it into scope.
You Standard RC.
Ah, see, that's because I left out.
There we go.
All right, so now we have RC in scope.
So now we'll say let se one equals RC new, create a new reference counter and then we'll say string
from and we'll just say pointer.
And then to create references to our string, we'll say s one dot clone and then we can also clone as
to because it points to the same value on the heap.
And then just to prove that they all point to the same value, we'll print them all out.
We have as one, as two and as three.
And now if we run this.
We see that we have pointer pointer, pointer pointer printed out three times.
So in this we have an RC value pointed to a heap allocated string which is going to have a reference
count associated with it.
Cloning and RC does not copy the value.
It creates another pointer to it and increment the reference count.
So again, in this example, the string pointer has a reference count of three and SW one, SW two and
SW three, which are all on the stack, all point to the string that is located on the heap.
Our data being a string, we are still able to use string methods as usual directly.
And I can.
I'll show this to you by saying s one dot contains and then in here we want to make sure it contains
point and then just to show that all the other ones are able to do it as well.
We'll say contains in this one and we'll say ter so we would expect our output to now be true.
Pointer And true and we have true.
Pointer True, which is what we anticipated.
And that's really again all there is to it, to RC and AAC.
So now in the next lecture we're going to talk about ref cell.