Derive for structs containing raw pointer

I am a bit confused on how derive works for a struct containing a parametric raw pointer

struct Int {
    el: isize,

#[derive(Copy, Clone)]
struct Ptr<T> {
    ptr: *const T,

fn main() {
    let x = Int { el: 0 };
    let ptr = Ptr { ptr: &x };
    let ptr2 = ptr;
    let ptr3 = ptr;

does not compile because Ptr<Int> does not implement Copy (despite the derive).

I have tried other traits and it seems that Ptr<T> can derive only traits implemented by T. I thought it was enough for *const T to implement those trait and that raw pointers are Copy, is this not the case?

As a follow up, does implementing Clone and Copy in the obvious way lead to any misbehavior (assuming I make sure that when I dereference a pointer it points to a valid location)?

Yeah, it's a bit unfortunate, but derives just copy the bounds onto any generic parameter. You want

impl<T> Copy for Ptr<T> { }
impl<T> Clone for Ptr<T> {
    fn clone(&self) -> Self {
        Ptr { ptr: self.ptr }

You can also use derivative if you find that to be too tedious.

FWIW, Clone can be implemented with Copy, just returning *self.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.