skip to content

Why does rustc reject a Rust type that derives `Copy` and also implements `Drop`, reporting error E0184?

level: middleimportance: should knowfreq 50%

answer

  1. silent duplicates versus one release
  2. a destructor means extra ownership
  3. count how often drop would run
  4. split the id from the owner

basics

~20 s

Copy promises that duplicating a value's bytes duplicates the whole value; Drop says the value owns something that must be released once. Silent copies would each run that release, freeing one resource twice, so rustc forbids the pair with E0184.

solid answer

~50 s

`Copy` values are duplicated implicitly on every assignment and call, and the compiler treats them as having nothing to clean up. A `Drop` impl says the opposite: the value manages a resource beyond its own bytes and its destructor must run exactly once. If both were allowed, every silent copy of a texture handle would be another owner, and each would run the destructor, freeing the texture several times. The standard library states it directly: any type implementing `Drop` can't be `Copy` because "it's managing some resource besides its own `size_of::<T>` bytes", and rustc rejects the pair with E0184. The rule is also transitive, because a `Copy` type's fields must all be `Copy`. The usual fix is to drop `Copy` and keep an explicit `Clone`, or to split a `Copy` id with no destructor from one owner type that implements `Drop`.

code

rust · 15 lines
rust
#[derive(Clone, Copy)]
struct TextureHandle {
    id: u32,
}

impl Drop for TextureHandle {
    fn drop(&mut self) {
        println!("free texture {}", self.id);
    }
}

fn main() {
    let a = TextureHandle { id: 7 };
    let _b = a;
}

go deeper

for a junior

Recall the rule: a type that implements Drop can never be Copy, and rustc reports E0184 when you try to combine them.

for a middle

Explain the mechanism: implicit copies would each run the destructor and release one resource several times, and the field rule makes it transitive.

for a senior

Show the repair you would choose in real code: drop Copy and keep Clone, or split a Copy id from one owner that implements Drop.

for a principal

Weigh the handle design: Copy ids keep systems decoupled but move release into one owner, which then defines lifetime policy for the whole engine.

## What each trait promises Two standard traits make opposite promises about a value: - **`Copy`** says that copying the value's bytes produces a complete, independent value. The compiler uses that promise to duplicate values **implicitly**: on `let b = a;`, on every by-value call, on every return. Nobody writes a line of code for those copies, and nobody sees them. - **`Drop`** says the value owns something outside its own bytes (a heap buffer, a file descriptor, a GPU texture, a slot in a pool) and that a destructor must run **exactly once**, when the owner goes away. A value cannot keep both promises. The `Copy` documentation puts it in one sentence: "any type implementing `Drop` can't be `Copy`, because it's managing some resource besides its own `size_of::<T>` bytes." ## Why the two cannot meet Picture a game handle that frees a GPU texture in its destructor, and imagine rustc allowed it to be `Copy`: 1. `let a = TextureHandle { id: 7 };` creates one handle. 2. `let b = a;` silently duplicates it, so two values now claim texture 7. 3. Passing `b` to a render helper by value makes a third copy. 4. Each copy goes out of scope and runs `drop`, freeing texture 7 three times. That is a double free (or a triple one), exactly the bug class ownership exists to prevent. Because the copies are implicit, the author would never see where they came from. rustc refuses the combination at the type definition: ```plaintext error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor 2 | struct TextureHandle { | ^^^^^^^^^^^^^ `Copy` not allowed on types with destructors ``` The error index describes E0184 as "the `Copy` trait was implemented on a type with a `Drop` implementation" and adds a nuance worth knowing: the combination is "currently disallowed" because the existing implementation would be incorrect and could lead to memory unsafety, even though the idea "can make some sense in theory". In practice the rule is absolute on stable Rust, and it applies to a hand-written `impl Copy` exactly as to a derive. ## The rule is transitive A `Copy` type's fields must all be `Copy`, and no `Copy` type has a destructor, so a `Copy` struct can never contain a field that needs dropping. Deriving `Copy` on a struct with a `String`, a `Vec` or a `TextureHandle` field fails with E0204, because those fields are not `Copy`. You can watch the consequence: on rustc 1.99.1, `std::mem::needs_drop::<Vec2>()` returns `false` for a plain `Copy` position type and `true` for `String` (the function is documented as a hint that may err towards `true`). One thing **is** allowed: a `Copy` struct may hold a shared reference to a type that implements `Drop`. Copying the struct copies the `&T` only; the referent still has one owner and one destructor run, and the borrow checker keeps every copy from outliving it. ## Fixing E0184 in a game codebase | Option | When it fits | |---|---| | Remove `Copy`, keep `Clone` | duplicates are rare and should be visible; a manual `clone` can register a new owner | | Copy id plus one owner | many places need the handle; one cache or pool frees the resource | | Shared reference in a `Copy` view | short-lived views that read the resource | The second option is the common design in engines: - a small `TextureId(u32)` derives `Clone, Copy` and has **no** destructor, so systems pass it around freely; - a single `TextureCache` owns the textures and implements `Drop`, so each texture is released exactly once. Reference-counted shared ownership is a third design, covered with smart pointers rather than here. ## What a strong answer covers 1. State the rule: a type with a `Drop` impl can never be `Copy`, derived or hand-written, and rustc reports E0184. 2. Give the reason: implicit copies would each run the destructor and release one resource several times. 3. Note the transitive consequence through the field rule (E0204), and the allowed case of a shared reference. 4. Propose a repair that fits the design: explicit `Clone`, or a `Copy` id plus a single owner. ## A related edge: dropping a Copy value Because a `Copy` value has no destructor, calling `std::mem::drop(v)` on one does nothing useful: `drop` receives a copy, and `v` stays usable. rustc warns about it with the default `dropping_copy_types` lint: "calls to `std::mem::drop` with a value that implements `Copy` does nothing". Seeing that warning is a sign the author believed the value owned something it does not.

  • What does `std::mem::drop(v)` do when `v` is `Copy`?
    Nothing useful. `drop` takes its argument by value, so it receives a copy and `v` stays usable afterwards; there is no destructor to run anyway. rustc's default `dropping_copy_types` lint warns: "calls to `std::mem::drop` with a value that implements `Copy` does nothing".
  • Can a `Copy` struct hold a reference to a type that implements `Drop`?
    Yes. `&T` is `Copy` for every `T`, so a struct whose only non-primitive field is `&'a Texture` can derive `Copy` even when `Texture` implements `Drop`. Copies duplicate the reference, the texture keeps one owner, and its destructor runs once when that owner drops.

  • Copy and Drop conflict only because the derive macro cannot combine them
  • Rust allows Copy with Drop and simply runs the destructor on each copy
  • A Copy struct may contain a field whose type implements Drop
  • Calling drop(v) on a Copy value releases it early
  • Removing the Drop impl is the only way to fix E0184