Is the drop order within scope deterministic without dependencies?

Given example case:

struct D(i32);
impl Drop for D {
  fn drop(&mut self) { println!("dropped {}", self.0); }
}

fn main() {
  {
    D(0);
    let x = D(1);
    let _ = D(2);
    D(3);
    let y = D(4);
    let _ = D(5);
  }
}

The actual execution emits

dropped 0
dropped 2
dropped 3
dropped 5
dropped 4
dropped 1

Is this implementation defined? Could the last two drops happen the other way around resulting in full output

dropped 0
dropped 2
dropped 3
dropped 5
dropped 1
dropped 4

That is, when x and y have no dependencies between each other and both are defined in the same scope, is the drop order between x and y deterministic?

AFAIK yes, variables are always dropped in reverse order of declaration. See the Reference.

1 Like

That's reverse order of declaration, not initialization.

1 Like

It's deterministic but complicated. Temporaries which are not bound are dropped at the end of their temporary scope, and variables are dropped at the end of the block in reverse order of declaration. Moreover, let _ = ... does not bind (but let _name = ... does). So D(2) and D(5) are still temporaries.

Thus, in your example, the temporaries drop in increasing order, and the named variables drop in decreasing order.

The drop order of non-temporaries is documented and thus supposedly guaranteed. The drop order of temporaries (in particular those subject to temporary lifetime extension) is somewhat more grey, as far as I understand. But I doubt the order of your explicit example can change.

3 Likes

Thanks. Indeed. I never do uninited declaration, so I missed that :slight_smile:

Note that in Rust, a statement

expression;

is equivalent to

let _ = expression;

with the only difference being that the latter silences some warnings about unused return values.

4 Likes

The Rust community is awesome! I had missed the part that declared variables drop in reverse order but other stuff drops in declaration order and I got multiple people giving references to the actual definition within half an hour!

Thanks!

1 Like