Why is std::rc::Rc<> not Copy?
有人可以向我解释为什么
我正在编写使用大量共享指针的代码,不得不一直输入
在我看来,
我想念什么吗?
It seems to me that
Rc<> should just consist of a pointer, which is a fixed size, so the type itself should beSized and henceCopy , right?
这不是真的。
但是我们如何保持参考计数器有效并保持最新状态?的确,每当创建新的引用/所有者或删除引用/所有者时,我们都必须做一些事情。具体来说,在前一种情况下,我们必须增加计数器,而在后一种情况下,我们必须减少计数器。
通过实现
但是我们什么时候进行增量?您猜对了:在
Types that can be copied by simply copying bits (i.e.
memcpy ).
在我们的情况下是不正确的,因为:是的,我们"只是复制位",但是我们还要做其他工作!我们确实需要增加我们的参考计数器!
-
Drop 的Drop 展示 -
Rc 的Clone 展示
如果类型实现
此外,
组成
1 2 3 | pub struct Rc<T: ?Sized> { ptr: Shared<RcBox< T >>, } |
又不仅是一个指针:
1 2 3 4 | pub struct Shared<T: ?Sized> { pointer: NonZero<*const T>, _marker: PhantomData< T >, } |
需要
this marker has no consequences for variance, but is necessary for
dropck to understand that we logically own aT .For details, see:
https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data