user1244932
user1244932

Reputation: 8112

Why is there a drop call after structure destructuring?

I am wrapping a C API. To simplify for this question, I'm using NonNull::dangling instead.

use std::ptr::NonNull;

struct Foo(NonNull<i32>);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Foo::drop: {:?}", self.0);
    }
}

struct Moo(NonNull<i32>);
//impl Drop for Moo exists, but not important for question

fn f1() -> Result<Foo, String> {
    Ok(Foo(unsafe { NonNull::dangling() }))
}

fn f2() -> Result<Moo, String> {
    f1().map(|Foo(x)| Moo(x))//1
}

fn main() {
    f2();
}

At point (1), I unpack/destructure Foo. I expect that after that, Foo::drop should not be called, but for some reason Foo::drop is printed.

Am I wrong that destructuring (let Struct1 { field1, field2, .. } = struct1;) should prevent the call of Struct1::drop?

Upvotes: 3

Views: 433

Answers (1)

Tim Diekmann
Tim Diekmann

Reputation: 8476

If you replace NonNull with a struct which does not implement Copy, the behavior is more clear:

#[derive(Debug)]
struct NoCopy;

struct Foo(NoCopy);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Foo::drop: {:?}", self.0);
    }
}

struct Moo(NoCopy);
//impl Drop for Moo exists, but not important for question

fn f1() -> Result<Foo, String> {
    Ok(Foo(NoCopy))
}

fn f2() -> Result<Moo, String> {
    f1().map(|Foo(x)| Moo(x))//1
}

fn main() {
    f2();
}

This results in this error:

error[E0509]: cannot move out of type `Foo`, which implements the `Drop` trait
  --> src/main.rs:20:15
   |
20 |     f1().map(|Foo(x)| Moo(x))//1
   |               ^^^^-^
   |               |   |
   |               |   data moved here
   |               cannot move out of here
   |
note: move occurs because `x` has type `NoCopy`, which does not implement the `Copy` trait
  --> src/main.rs:20:19
   |
20 |     f1().map(|Foo(x)| Moo(x))//1
   |            

Therefore, in (1) you copy the NonNull out of Foo and Foo gets dropped.

Upvotes: 6

Related Questions