patternrustMajor
Why is std::rc::Rc<> not Copy?
Viewed 0 times
whycopynotstd
Problem
Can someone explain to me why
I'm writing code that uses a lot of shared pointers, and having to type
It seems to me that
Am I missing something?
Rc<> is not Copy?I'm writing code that uses a lot of shared pointers, and having to type
.clone() all the time is getting on my nerves.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?Am I missing something?
Solution
It seems to me that
This is not quite true.
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
But when do we do the increment? You guessed it: in
Types that can be copied by simply copying bits (i.e.
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!
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!
Dropimpl ofRc
Cloneimpl ofRc
Context
Stack Overflow Q#40014703, score: 80
Revisions (0)
No revisions yet.