Why is std::rc::Rc<> not Copy?

前端 未结 2 1209
悲哀的现实
悲哀的现实 2020-12-15 17:34

Can someone explain to me why Rc<> is not Copy?

I\'m writing code that uses a lot of shared pointers, and having to type .clone

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 17:52

    A type cannot implement Copy if it implements Drop (source). Since Rc does implement it to decrement its reference count, it is not possible.

    In addition, Rc is not just a pointer. It consists of a Shared:

    pub struct Rc {
        ptr: Shared>,
    }
    

    Which, in turn, is not only a pointer:

    pub struct Shared {
        pointer: NonZero<*const T>,
        _marker: PhantomData,
    }
    

    PhantomData is needed to express the ownership of T:

    this marker has no consequences for variance, but is necessary for dropck to understand that we logically own a T.

    For details, see: https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data

提交回复
热议问题