Avoid copy/clone of a value

I'm writing some unsafe code and it has a pointer whose lifetime is managed manually by the library logic. Right now I just have a comment over the struct field that says that this value must not be copied. Is it possible to enforce this constraint using the type system? Maybe a NoCopy wrapper that causes a compilation error if the code tries copying/cloning this field containing the pointer?

You could define a newtype that doesn’t implement Copy or Clone to hold the pointer:

#[repr(transparent)]
struct NonCopyPtr<T:?Sized>(pub mut* T)
3 Likes

Wouldn't let p = non_copy_ptr.0 make a copy?

Yes, but it will prevent a Copy or Clone derive from being added to the containing struct. You can also remove the pub from the field to prevent external code from being able to make a copy, leaving only what you explicitly allow.

Preventing absolutely all copies would be counter-productive, as then there would be no way to access the memory that the pointer points to.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.