What is Rc?
Limitation of Box
Is it possible to mutate a value of type Rc?
How it works under the hood?
struct Rc<T> {
ref_value: &'static T,
ref_counter: &'static usize,
// Here the static lifetime parameter signifies that the value and counter are stored in heap.
}
// When a Rc is cloned, we increment the counter to keep track of number of active references.
// Then we copy the reference to the value and the counter.
// NOTE: The actual value in the heap is not copied.
impl Rc<T> {
fn clone(&mut self) -> Self {
unsafe {
*self.ref_counter += 1;
}
Rc {
ref_value: self.ref_value,
ref_counter: self.ref_counter,
}
}
}
// When a Rc value goes out of scope the drop method of the Drop trait is invoked.
// It works like the below demonstration
impl Drop<T> for Rc<T> {
fn drop(&mut self) {
unsafe {
*self.ref_counter -= 1;
if *self.ref_counter <= 0 {
free(self.ref_counter);
free(self.ref_value);
// Refering to os free sys call
// Look into linux man page https://linux.die.net/man/3/free
}
}
}
}Question
Example where the compiler cannot determine when the reference count will become zero
Last updated