Skip to content

Destructor call order #4456

@AngryLawyer

Description

@AngryLawyer
struct Outer {
    inner: Inner
}

impl Outer : Drop {
    fn finalize(&self) {
        io::println("Outer has been dropped");
    }
}

struct Inner {
    dummy: bool
}

impl Inner : Drop {
    fn finalize(&self) {
        io::println("Inner has been dropped");
    }
}

fn main() {
    let outer = Outer{
        inner: Inner{
            dummy: true
        }
    };

I'd have expected the output to be as so

Inner has been dropped
Outer has been dropped

But we get

Outer has been dropped
Inner has been dropped

Is this correct? There are cases when you're interfacing with external libs where stuff needs to be created in one order, and then destroyed in reverse, such as with SDL creating and releasing a surface should only happen in between Init and Exit commands. The way it currently stands means the outermost object gets its destructor called first, which means bad things happen.

Am I missing the correct way to do this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-destructorsArea: Destructors (`Drop`, …)A-runtimeArea: std's runtime and "pre-main" init for handling backtraces, unwinds, stack overflows

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions