Skip to content

Do not derive Clone/Copy/etc for opaque types #1656

Open
@VeaaC

Description

@VeaaC
Contributor

Currently bindgen will generate code that derives for opaque types, e.g.:

typedef struct MyOpaqueStruct MyOpaqueStruct;
#[derive(Copy, Clone, Debug)]
pub struct MyOpaqueStruct {
    _unused: [u8; 0],
}

This has several problems:

  • If a user can obtain a reference to a type they can clone it, even though that is normally only possible through FFI calls, and will almost always result in UB
  • It prevents a user from implementing those traits on their own

The only current solution seems to be to turn of those derivations completely, forcing a user to implement them manually on the non-opaque types.

I would suggest to just not derive any of these in case of an opaque struct (since I cannot come up with a use-case were they would actually work)

Activity

emilio

emilio commented on Oct 28, 2019

@emilio
Contributor

This makes sense... I can see a few cases where it'd work, but yeah, it's sketchy at best.

jschwe

jschwe commented on Feb 5, 2025

@jschwe
Contributor
#[derive(Copy, Clone, Debug)]
pub struct MyOpaqueStruct {
    _unused: [u8; 0],
}

Probably worth mentioning that in the bindgen code, these are "forward declared types".
E.g. the opaque annotation does not cause bindgen to generate a struct like the above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @emilio@VeaaC@jschwe

      Issue actions

        Do not derive Clone/Copy/etc for opaque types · Issue #1656 · rust-lang/rust-bindgen