Skip to content

Member destructor is always executed even if self is replaced in Drop #23611

Closed
@nwin

Description

@nwin

The following code prints "Dropping!" although the corresponding variant had been removed and forgotten. Same happens if it is overwritten instead.

use std::mem;
use std::ptr;

struct Noisy;
impl Drop for Noisy {
    fn drop(&mut self) { println!("Dropping!") }
}

enum Foo {
    Bar(Noisy),
    Baz
}
use Foo::*;

impl Drop for Foo {
    fn drop(&mut self) {
        match *self {
            Bar(_) => {
                //unsafe { ptr::write(self, Foo::Baz) }
                unsafe { mem::forget(mem::replace(self, Foo::Baz)) }
            }
            Baz => ()
        }
    }
}

fn main() {
    let _ = Foo::Bar(Noisy);
}

I’m not sure if this is a bug or intended behavior but it is not obvious to me that this would happen and might be documented in more detail.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions