It seems to me that Rc<>
should just consist of a pointer, which is a fixed size, so the type itself should be Sized
and hence Copy
, right?
This is not quite true. Rc
is short for Reference Counted. This means that the type keeps track of how many references point to the owned data. That way we can have multiple owners at the same time and safely free the data, once the reference count reaches 0.
But how do we keep the reference counter valid and up to date? Exactly, we have to do something whenever a new reference/owner is created and whenever a reference/owner is deleted. Specifically, we have to increase the counter in the former case and decrease it in the latter.
The counter is decreased by implementing Drop
, the Rust equivalent of a destructor. This drop()
function is executed whenever a variable goes out of scope – perfect for our goal.
But when do we do the increment? You guessed it: in clone()
. The Copy
trait, by definition, says that a type can be duplicated just by copying bits:
Types that can be copied by simply copying bits (i.e. memcpy
).
This is not true in our case, because: yes, we "just copy bits", but we also do additional work! We do need to increment our reference counter!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…